【问题标题】:Converting text file to YAML in Python在 Python 中将文本文件转换为 YAML
【发布时间】: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 格式:

  1. 使用正则表达式将等号替换为冒号。
  2. Section section_name 替换为section_name :
  3. 删除每个部分之间的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 不需要在字符串周围加上引号,除非存在特殊字符。源文件中没有单引号或双引号。
  • 在这种情况下,在输入文件中提及所有数据类型具有误导性,因为您只想复制这些值。这里唯一无效的是您对问题的描述,现在看来是微不足道的。

标签: python yaml python-re


【解决方案1】:

我宁愿将其转换为 dict,然后使用 python 中的 yaml 包将其格式化为 yaml,如下所示:

import yaml
def convert_txt_to_yaml(file_content):
    """Converts a text file to a YAML file"""
    config_dict = {}
    
    # Split the lines 
    lines = file_content.splitlines()
    section_title=None
    for line in lines:
        if line=='\n':
            continue
        elif re.match('.*end$', line):
            #End of section
            section_title=None
        elif re.match('.*Section\s+.*', line):
            #Start of Section
            match_obj =  re.match(".*Section\s+(.*)", line)
            section_title=match_obj.groups()[0]
            config_dict[section_title] = {}
        elif section_title and re.match(".*{}_.*\s+=.*".format(section_title), line):
            match_obj =  re.match(".*{}_(.*)\s+=(.*)".format(section_title), line)            
            config_dict[section_title][match_obj.groups()[0]] = match_obj.groups()[1]
    return yaml.dump(config_dict )

【讨论】:

  • 非常感谢这个 Arun,它从概念上解决了我关于部分开头和结尾的问题,但是输出是一个错误并且不再打印值。我将独立完成这项工作,但如果您有任何建议,我们将不胜感激
  • 你能告诉我你遇到了什么错误吗?因为当我尝试时,我看不到任何错误和正确的 YAML 被转储了。
  • 我得到这个错误:stackoverflow.com/questions/25584124/… 这显然是可以修复的。所以你解决了我的问题。
猜你喜欢
  • 2020-11-14
  • 2012-10-12
  • 1970-01-01
  • 2018-11-23
  • 2011-06-22
  • 1970-01-01
  • 1970-01-01
  • 2016-11-24
  • 1970-01-01
相关资源
最近更新 更多