繁体   English   中英

如何根据文件中的字符串创建字典

[英]How to create a dictionary based on a string from a file

我在文本文件中有以下字符串

InfoType 0 :

string1

string2

string3

InfoType 1 :

string1

string2

string3

InfoType 3 :

string1

string2

string3

有没有办法创建一个看起来像这样的字典:

{'InfoType 0':'string1,string2,string3', 'InfoType 1':'string1,string2,string3', 'InfoType 3':'string1,string2,string3'}

像这样的东西应该工作:

def my_parser(fh, key_pattern):
    d = {}
    for line in fh:
        if line.startswith(key_pattern):
            name = line.strip()
            break

    # This list will hold the lines
    lines = []

    # Now iterate to find the lines
    for line in fh:
        line = line.strip()
        if not line:
            continue

        if line.startswith(key_pattern):
            # When in this block we have reached 
            #  the next record

            # Add to the dict
            d[name] = ",".join(lines)

            # Reset the lines and save the
            #  name of the next record
            lines = []
            name = line

            # skip to next line
            continue

        lines.append(line)

    d[name] = ",".join(lines)
    return d

像这样使用:

with open("myfile.txt", "r") as fh:
    d = my_parser(fh, "InfoType")
# {'InfoType 0 :': 'string1,string2,string3',
#  'InfoType 1 :': 'string1,string2,string3',
#  'InfoType 3 :': 'string1,string2,string3'}

有一些限制,例如:

  • 重复键
  • 关键需要处理

您可以通过使 function 成为generator并生成name, str对并在您阅读文件时处理它们来解决这些问题。

这将做:

dictionary = {}

# Replace ``file.txt`` with the path of your text file.
with open('file.txt', 'r') as file:
    for line in file:
        if not line.strip():
            continue

        if line.startswith('InfoType'):
            key = line.rstrip('\n :')
            dictionary[key] = ''
        else:
            value = line.strip('\n') + ','
            dictionary[key] += value

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM