对于行:不返回所有行

For line in : not returning all lines

我正在尝试遍历一个文本文件并将每一行放入字典中。前任: 如果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)

我的字典只包含部分列表。如果我使用这段代码(不是试图构建字典,只是测试):

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'))

这解决了一些问题。

  1. 函数不应该有硬编码变量,而应该使用参数。这样你就可以重用这个函数了。
  2. 函数应该(通常)return 值而不是打印它们。这允许您在进一步计算中使用函数的结果。
  3. 您使用的是手动索引变量,而不是使用内置 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

这是因为您调用了 readline() 函数两次。简单地做:

def word_dict():
    fin = open('words2.txt','r')
    dict_words = dict()
    i = 1
    for line in fin:
        txt = line.strip()
        dict_words.update({txt: i})
        i += 1
    print(dict_words)