逐行读取和解析文件中的字符串 - 数据源文件数据不按顺序或模式进行数据追加



这个问题是为了澄清我在处理文件源中的字符串并将其附加到字典键列表时遇到的一个问题,该列表是从另一个 SO 问题扩展而来的。这是下面的示例源文件:

 Name: David
 Age: 23
 Name: Ally
 Age: 21
 Age: 20
 Name: John
 Name: Peter
 Age: 22
如果您注意到文件有名称,年龄,名称,年龄,突然年龄,名称

并返回名称,年龄...这可能会发生在文件中的任何行上(在名称和年龄之间扭曲(。

如果一切都以名称开头并以年龄结尾;那么我可以使用以下代码将其一一读取并解析到字典列表中:

file = open("file")
data = file.readlines()
data = [i.strip() for i in data]
dict_ = {"Person":[]}
for i in range(0,len(data),2):
    line = data[i].split(':')
    nxt_line = data[i+1].split(':')
    dict_['Person'].append({'Name':line[1], 'Age': nxt_line[1]})
问题是当数据

文件中的某些名称和年龄行扭曲时,作为上面的数据文件的示例,并且当运行代码时,值被错误解析。

如何确保名称和年龄的值可以正确传递到字典,即使名称和年龄在源文件中的位置颠倒并且不遵循顺序。

请指教。谢谢。

试试这个:

file = open("temp2.txt")
data = file.readlines()
data = [i.strip() for i in data]
dict_ = {"Person":[]}
for i in range(0,len(data),2):
    line = data[i].split(':')[1].strip()  # Remove the leading spaces of the second split item
    nxt_line = data[i+1].split(':')[1].strip()  # Remove the leading spaces of the second split item in the next line
    if line.isnumeric():  # 'any_int'.isnumeric() returns True
        dict_['Person'].append({'Name':nxt_line, 'Age': line})
    else:  # If the string is not numeric type, it must be the name
        dict_['Person'].append({'Name':line, 'Age': nxt_line})

输出

{'Person': [{'Name': 'David', 'Age': '23'}, {'Name': 'Ally', 'Age': '21'}, {'Name': 'John', 'Age': '20'}, {'Name': 'Peter', 'Age': '22'}]}

一种方法是每两行配对一次。

前任:

with open(filename) as infile:
    data = [i.strip() for i in infile.readlines()]
data = [data[i:i+2] for i in range(0, len(data), 2)]    #Divide line to chunks of 2. 
result = []
for m, n in data:
    val = dict([m.split(":")])
    val.update(dict([n.split(":")]))
    result.append(val)    
print(result)

输出:

[{'Age': ' 23', 'Name': ' David'},
 {'Age': ' 21', 'Name': ' Ally'},
 {'Age': ' 20', 'Name': ' John'},
 {'Age': ' 22', 'Name': ' Peter'}]

最新更新