gpt4 book ai didi

python - 由于换行符,无法从文件创建字典

转载 作者:太空宇宙 更新时间:2023-11-03 11:13:52 27 4
gpt4 key购买 nike

我有一个看起来像这样的文件:

Mother Jane
Father Bob
Friends Ricky,Jack,Brian,Jordan, \
Ricardo,Sonia,Blake

如您所见,我在“Friends”第一行的末尾有一个换行符。当我想将此文件解析为字典时,我当前的代码出现错误。

我在网上寻找解决方案并尝试了多种方法,但似乎没有任何效果。

with open('./file.txt') as f:
content = f.readlines()

dic = {}
for line in content:
line_items = line.strip().split()
if len(line_items) <= 2:
dic[line_items[0]] = line_items[1]
else:
dic[line_items[0]] = line_items[1:]

我想要一个看起来像这样的结果:

dict = {"Mother": "Jane", "Father": "Bob","Friends":[Ricky,Jack,Brian,Jordan,Ricardo,Sonia,Blake]

但是我得到了一个超出索引的错误。

最佳答案

以下似乎有效。它将多行收集到一个逻辑行中,然后对其进行处理。它也不会将整个文件读入内存。

from pprint import pprint, pformat

dic = {}
with open('./newline_file.txt') as f:
lst = []
for line in iter(f.readline, ''):
line = line.strip()
if line[-1] == '\\': # Ends with backslash?
lst.append(line[:-2])
continue
else:
lst.append(line)
logical_line = ''.join(lst)
lst = []

line_items = logical_line.split(' ')
if len(line_items) == 2:
if ',' in line_items[1]:
dic[line_items[0]] = line_items[1].split(',')
else:
dic[line_items[0]] = line_items[1]

pprint(dic)

输出:

{'Father': 'Bob',
'Friends': ['Ricky', 'Jack', 'Brian', 'Jordan', 'Ricardo', 'Sonia', 'Blake'],
'Mother': 'Jane'}

关于python - 由于换行符,无法从文件创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55483255/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com