文本到词典不匹配

2024-05-29 09:48:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我的Python代码所在的文件夹中有以下文本文件。你知道吗

78459581
Black Ballpoint Pen
12345670
Football
49585922
Perfume
83799715
Shampoo

我已经写了这个Python代码。你知道吗

file = open("ProductDatabaseEdit.txt", "r")
d = {}
for line in file:
    x = line.split("\n")
    a=x[0]
    b=x[1]
    d[a]=b

print(d)

这是我收到的结果。你知道吗

b=x[1]  # IndexError: list index out of range

我的字典应该出现如下:

{"78459581" : "Black Ballpoint Pen"
 "12345670" : "Football"
 "49585922" : "Perfume"
 "83799715" : "Shampoo"}

我做错什么了?你知道吗


Tags: 代码intxt文件夹forlineopenperfume
3条回答

您可以使用dictionary generator简化您的解决方案,这可能是我能想到的最具python风格的解决方案:

>>> with open("in.txt") as f:
...   my_dict = dict((line.strip(), next(f).strip()) for line in f)
... 
>>> my_dict
{'12345670': 'Football', '49585922': 'Perfume', '78459581': 'Black Ballpoint Pen', '83799715': 'Shampoo'}

其中in.txt包含问题中描述的数据。必须strip()每一行,否则会留下一个\n字符作为键和值的尾部。你知道吗

换行符以换行符结束,因此line.split("\n")不会给您多行。你知道吗

你可以作弊并做:

for first_line in file:
    second_line = next(file)

您需要剥去\n而不是分开

file = open("products.txt", "r")
d = {}
for line in file:
    a = line.strip()
    b = file.next().strip()
    # next(file).strip() # if using python 3.x
    d[a]=b

print(d)

{'12345670': 'Football', '49585922': 'Perfume', '78459581': 'Black Ballpoint Pen', '83799715': 'Shampoo'}

相关问题 更多 >

    热门问题