【发布时间】:2020-08-03 09:03:31
【问题描述】:
我有一个要转换为 YAML 格式的文本文件。这里有一些注释可以更好地描述这个问题:
- 文件中的各个部分有不同数量的子标题。
- 子标题的值可以是任何数据类型(例如 string、bool、int、double、datetime)。
- 该文件大约有 2,000 行。
格式示例如下:
file_content = '''
Section section_1
section_1_subheading1 = text
section_1_subheading2 = bool
end
Section section_2
section_2_subheading3 = int
section_2_subheading4 = double
section_2_subheading5 = bool
section_2_subheading6 = text
section_2_subheading7 = datetime
end
Section section_3
section_3_subheading8 = numeric
section_3_subheading9 = int
end
'''
我尝试通过以下方式将文本转换为 YAML 格式:
- 使用正则表达式将等号替换为冒号。
- 将
Section section_name替换为section_name :。 - 删除每个部分之间的
end。
但是,我对#2 和#3 有困难。这是我目前创建的 text-to-YAML 函数:
import yaml
import re
def convert_txt_to_yaml(file_content):
"""Converts a text file to a YAML file"""
# Replace "=" with ":"
file_content2 = file_content.replace("=", ":")
# Split the lines
lines = file_content2.splitlines()
# Define section headings to find and replace
section_names = "Section "
section_headings = r"(?<=Section )(.*)$"
section_colons = r"\1 : "
end_names = "end"
# Convert to YAML format, line-by-line
for line in lines:
add_colon = re.sub(section_headings, section_colons, line) # Add colon to end of section name
remove_section_word = re.sub(section_names, "", add_colon) # Remove "Section " in section header
line = re.sub(end_names, "", remove_section_word) # Remove "end" between sections
# Join lines back together
converted_file = "\n".join(lines)
return converted_file
我相信问题出在for 循环中 - 我无法弄清楚为什么部分标题和结尾没有改变。如果我测试它会完美打印,但线条本身并没有保存。
我正在寻找的输出格式如下:
file_content = '''
section_1 :
section_1_subheading1 : text
section_1_subheading2 : bool
section_2 :
section_2_subheading3 : int
section_2_subheading4 : double
section_2_subheading5 : bool
section_2_subheading6 : text
section_2_subheading7 : datetime
section_3 :
section_3_subheading8 : numeric
section_3_subheading9 : int
'''
【问题讨论】:
-
您要查找的输出格式是什么?
-
嗨@AbhijitSarkar,我刚刚添加了输出格式。谢谢你的提醒。
-
如何知道源文件中的
13是字符串,还是输出文件中的数字?您需要澄清您的问题,缺少基本事实。 -
我不知道这是否是一个有效的“基本事实”,考虑到 YAML 不需要在字符串周围加上引号,除非存在特殊字符。源文件中没有单引号或双引号。
-
在这种情况下,在输入文件中提及所有数据类型具有误导性,因为您只想复制这些值。这里唯一无效的是您对问题的描述,现在看来是微不足道的。