簡體   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