HartX
@HartX
Студент, красавчик, плохой программист=)

Как записывать обычные строки и пропуски строк в .yml файл с помощью python?

Делаю автоматический перевод одной игрушки. Я беру строки из yml файла, перевожу и хочу записать обратно по аналогии. Вот кусочек такого файла:
l_english:
  bos_justice:0 "Justice"
  bos_justice_desc:0 "On October 10th 2077, less than a week before nuclear fire destroyed all that was and had been, Robert Maxson and his followers descended upon the West-Tek facility in hopes of finding resources and supplies. Instead, they found a freak show, a nightmarish realm of FEV and mad scientists. Robert was furious, and what he decided to do with these mad men would echo through the centuries."

  bos_glow:0 "The Glow"
  bos_glow_desc:0 "In 2134, after the formal formation of the Brotherhood of Steel, a splinter faction lead by Dennis Allen, who was among Maxson's original soldiers, requested permission to return to the West-Tek facility in search of technological artefacts. Understanding fully that this was the most dangerous mission ever presented to the council, he trusted his good reputation to garner him permission."

  bos_vipers:0 "The Vipers"
  bos_vipers_desc:0 "The War with the Vipers was a skirmish like any other, routine patrols engaging in small and one sided firefights with random raider gangs. But this time it was different, this time there were casualties. Maxson himself died hours after the engagement, writing in pain as radscorpion venom claimed him. This painful and horrific death lead to outrage among the Brotherhood of Steel."

  bos_oldamerica:0 "Old America"
  bos_oldamerica_desc:0 "The Brotherhood was not the only pre-war military outfit to survive the end of America, and that became overwhelmingly apparent with the rise of the Enclave. After years of passive observation and subtle manoeuvring, the Brotherhood of Steel joined the NCR in the final battle at the Navarro Outpost. This was in many ways, the opening of a new Chapter for the Brotherhood of Steel."

 # Underground Hangars sub-tree

  bos_hangars:0 "Underground Hangars"
  bos_hangars_desc:0 "Some Pre-War Military Bunkers come equipped with underground hangars, allowing Vertibird storage in relative safety and obscurity. Many of these facilities also come with facilities for repair and ample fuel storage. Bringing them back online is necessary for power protection."

Я не понимаю как мне с помощью библиотеки yaml в python делать строки типа # Underground Hangars sub-tree и пустые строки. Так же мой код (вот он):
import yaml

to_yaml = {'l_english': [{'bos_justice': '0 text'}, {'bos_justice_desc': '0 text'}]}

with open('sw_templates.yaml', 'w') as f:
    yaml.dump(to_yaml, f, default_flow_style=False)


Делает лишний пробел между : и 0 и ставит чёрточки перед строками.
l_english:
- bos_justice: 0 text
- bos_justice_desc: 0 text

Я не могу даже найти примеров построения подобного yml файла. Подскажите пожалуйста как мне это сделать
  • Вопрос задан
  • 189 просмотров
Решения вопроса 1
phaggi
@phaggi Куратор тега Python
лужу, паяю, ЭВМы починяю
Списки по-умолчанию превращаются в yaml «с черточками», а словари - без чёрточек.
Что касается # - в стандарте синтаксиса yaml это означает комментарии. По ссылке вычитал, что в pyyaml комменты запихать трудно, и проще использовать другую библиотеку - ruamel.yaml

Что касается пробелов после двоеточия - боюсь, кроме как постобработкой от них не избавиться.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
19 апр. 2024, в 05:01
999999 руб./за проект
19 апр. 2024, в 03:52
1000 руб./за проект
19 апр. 2024, в 03:01
1000 руб./за проект