Noo*_*123 4 python dictionary readlines
我试图遍历一个文本文件,并采取每一行,并将其放入字典.例如:如果txt文件是b c
我正在尝试创建一个字典
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)
Run Code Online (Sandbox Code Playgroud)
我的词典只包含部分列表.如果我使用此代码(不尝试构建字典,只需测试):
def word_dict():
fin = open('words2.txt','r')
i = 1
while fin.readline():
txt = fin.readline().strip()
print(i,'.',txt)
i += 1
Run Code Online (Sandbox Code Playgroud)
一样.它会打印一个不完整的值列表.该列表与字典值匹配.我错过了什么?
你试图两次阅读这些行.
这样做:
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'))
Run Code Online (Sandbox Code Playgroud)
这修复了一些事情.
return
值而不是打印它们.这允许您在进一步计算中使用函数的结果.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
Run Code Online (Sandbox Code Playgroud)