python - 对于 : not returning all lines 中的行

标签 python dictionary readlines

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

这解决了一些问题。

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

关于python - 对于 : not returning all lines 中的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464521/

相关文章:

python - 在维度内建立索引的最简单方法

python - Python 中的 Dota 2 API (dota2api) 库

python - 查找字母、数字或符号组

c++ - 为 C++ 中的可枚举寻找合适的容器/函数

python - 字典列表继续覆盖 - 我做错了什么?

python - 为什么我的 if 语句不能正确执行?

python - golang <--> python 通信的最简单的 pub-sub 通信,可能跨机器?

python - 将字符串转换为字典的简单方法

python - 检查文本文件中的日期是否过期

Python 使用名称和分数对文件进行排序