我想将文本文件中的所有单词添加到字典中,但只将一次(不重复)和其余单词添加到列表中。通过查看答案,我已经想出了如何做到这一点。这就是我放弃时代码的样子。当我在一个文本文件上运行它时,我得到了文件中最后一个单词的keyerror。这种方式非常接近解决方案,但我无法让它正常运行,我不明白为什么。有人请尝试向我解释这一点,以便我可以更好地理解。谢谢。
import sys
def dictionary(filename):
dict = {}
list = []
open_file = open(filename, 'rU')
for lines in open_file:
line = lines.split()
for words in line:
word = words.lower()
if not word in dict:
dict[word]
else:
list.append(word)
print (dict)
filename = sys.argv[1]
dictionary(filename)
答案 0 :(得分:0)
您收到的是KeyError,因为您没有为字典中的键指定值。 Python中的字典最好被认为是无序的键/值对集合。请参阅文档here。
您可以通过为dict [word]分配一个值来修复错误,例如word:
dict[word] = word
答案 1 :(得分:0)
根据您的问题,您实际想要的似乎是set()
(“设置对象是不同的可清除对象的无序集合”)。 (如果我的假设是错误的,请评论我的答案。)
from sys import argv
def dictionary(filename):
words = set()
repeats = []
with open(filename, 'rU') as open_file:
for line in open_file:
for word in line.split():
word = word.lower()
if word in words:
repeats.append(word)
words.add(word)
return words
print dictionary(argv[1])
您的代码存在一些问题。首先,KeyError
被引发,因为您从未为字典中的项目指定值。 (我怀疑这是因为实际上没有任何值与键匹配,但是你使用了字典,因为字典中没有重复键。)第二个问题是你的if... else
语句的缩进。我最后的改变是使用with... as
构造来打开文件,这有很多好处(例如即使有例外也关闭文件)。我希望我能正确地解释你的问题,这个答案对你有帮助。