Python 线性搜索包含数据的文件和包含单词的文件(例如,拼写检查)
我不确定为什么我的代码不起作用。这是一个我必须实现的程序的函数Python 线性搜索包含数据的文件和包含单词的文件(例如,拼写检查),python,Python,我不确定为什么我的代码不起作用。这是一个我必须实现的程序的函数 def spellcheck_list(document, dictionary): """ Checks the spelling of each word in 'document' (a list of words) against the dictionary (another list of words). """ pos = 0 found = False stop
def spellcheck_list(document, dictionary):
"""
Checks the spelling of each word in 'document' (a list of words) against
the dictionary (another list of words).
"""
pos = 0
found = False
stop = False
for word in document:
while pos < len(dictionary) and found:
if document[pos] in dictionary:
found = True
else:
pos = pos+1
print word
def拼写检查列表(文档、词典):
"""
检查“文档”(单词列表)中每个单词的拼写是否与
字典(另一个单词列表)。
"""
pos=0
发现=错误
停止=错误
对于文档中的word:
而pos
主循环中存在许多问题
最初是found
,因此False
循环将永远不会执行while
是文档中的单词,word
是词典中的当前位置。因此,在字典中检查pos
文档[pos]没有什么意义
for word in document:
if not word in dictionary
print word
…虽然很难准确地说出您希望代码执行的操作。有什么问题?我想一切都很好 什么是停止
pos
与dictional
或文档相关吗
解决方案:
我建议如下:
def print_iter(f):
def replacefunc(*a, **k):
for i in f(*a, **k): print i
return replacefunc
@print_iter # for debugging purposes. Remove it to get a generator function.
# Until here it is just "sugar".
def spellcheck_list(document, dictionary):
"""
Checks the spelling of each word in 'document' (a list of words) against
the dictionary (another list of words).
"""
dictset = set(dictionary) # but better have the caller do that
for word in document:
if word in dictionary:
yield word
以后,如果您将字典
作为集()
“过早地”使用,您甚至可以使用一行程序:
correct_words = (word for word in document if word in dictionary)
wrong_words = (word for word in document if word not in dictionary)
代码的其余部分在哪里?字典?文件?哦,对不起。。它们都是文件。“不工作”不是一个有用的故障描述我希望我的代码打印出字典中没有的每个单词(包含单词的文件),在这种情况下,我认为我的循环或多或少是你想要的。我不这么认为。什么是代码>?非常感谢。。它起作用了。。花了一段时间核对了1000个单词。。我想这就是为什么我们必须使用哈希来代替。。但是谢谢你。@glglgl-我已经有一段时间没有写Python了。我忘了,它没有符号布尔运算符(| |->或,&&->和,!->没有)?
if document[pos] in dictionary:
found = True
else:
pos = pos+1
print word
def print_iter(f):
def replacefunc(*a, **k):
for i in f(*a, **k): print i
return replacefunc
@print_iter # for debugging purposes. Remove it to get a generator function.
# Until here it is just "sugar".
def spellcheck_list(document, dictionary):
"""
Checks the spelling of each word in 'document' (a list of words) against
the dictionary (another list of words).
"""
dictset = set(dictionary) # but better have the caller do that
for word in document:
if word in dictionary:
yield word
correct_words = (word for word in document if word in dictionary)
wrong_words = (word for word in document if word not in dictionary)