【发布时间】:2020-02-12 10:28:16
【问题描述】:
此代码用于读取文本文件并将每个单词添加到字典中,其中键是第一个字母,值是文件中以该字母开头的所有单词。它有点工作,但对于 我遇到了两个问题:
- 字典键包含撇号和句号(如何排除?)
- 这些值不是按字母顺序排列的,而且都是乱七八糟的。代码最终输出如下内容:
' - {"don't", "i'm", "let's"}
. - {'below.', 'farm.', 'them.'}
a - {'take', 'masters', 'can', 'fallow'}
b - {'barnacle', 'labyrinth', 'pebble'}
...
...
y - {'they', 'very', 'yellow', 'pastry'}
什么时候应该更像:
a - {'ape', 'army','arrow', 'arson',}
b - {'bank', 'blast', 'blaze', 'breathe'}
etc
# make empty dictionary
dic = {}
# read file
infile = open('file.txt', "r")
# read first line
lines = infile.readline()
while lines != "":
# split the words up and remove "\n" from the end of the line
lines = lines.rstrip()
lines = lines.split()
for word in lines:
for char in word:
# add if not in dictionary
if char not in dic:
dic[char.lower()] = set([word.lower()])
# Else, add word to set
else:
dic[char.lower()].add(word.lower())
# Continue reading
lines = infile.readline()
# Close file
infile.close()
# Print
for letter in sorted(dic):
print(letter + " - " + str(dic[letter]))
我猜我在第一次遍历文件时需要从整个文件中删除标点符号和撇号,但在向字典中添加任何内容之前?但是,在以正确的顺序获取值时完全迷失了。
【问题讨论】:
-
问题是你正在遍历单词中的每个字符,然后将单词添加到该键中。只需取第一个字符,即
word[0],然后检查它是否为.isalpha() -
注意,永远不要像那样循环文件,文件对象是文件中行的迭代器,所以你可以这样做
for line in infile: ...
标签: python dictionary set