我正在尝试遍历一个文本文件并将每一行放入字典中。前任: 如果txt文件是 一种 b
我正在尝试创建一个像这样的字典
word_dict = {'a':1, 'b:2', 'c':3}
当我使用这段代码时:
def word_dict():
fin = open('words2.txt','r')
dict_words = dict()
i = 1
for line in fin:
txt = fin.readline().strip()
dict_words.update({txt: i})
i += 1
print(dict_words)
我的字典只包含部分列表。如果我使用此代码(不是尝试构建字典,只是测试):
def word_dict():
fin = open('words2.txt','r')
i = 1
while fin.readline():
txt = fin.readline().strip()
print(i,'.',txt)
i += 1
同样的事情。它打印不完整的值列表。不过,该列表与字典值匹配。我错过了什么?
最佳答案
您正在尝试阅读这些行两次。
只需这样做:
def word_dict(file_path):
with open(file_path, 'r') as input_file:
words = {line.strip(): i for i, line in enumerate(input_file, 1)}
return words
print(word_dict('words2.txt'))
这解决了一些问题。
- 函数不应该有硬编码变量,而应该使用参数。这样您就可以重用该函数。
- 函数应该(通常)
返回
值而不是打印它们。这允许您在进一步计算中使用该函数的结果。 - 您使用的是手动索引变量,而不是使用内置的
enumerate
。
这一行 {line.strip(): i for i, line in enumerate(input_file, 1)}
就是所谓的字典理解。它等效于以下代码:
words = {}
for i, line in enumerate(input_file, 1):
words[line.strip()] = i
关于python - 对于 : not returning all lines 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464521/