Python检查列表中的单词

Python检查列表中的单词,python,python-3.x,Python,Python 3.x,我正在编写一个拼写检查函数,我正在使用两个文本文件:一个是拼写错误的文本,另一个是包含字典中一堆单词的文本文件。我已将拼写错误的单词文本转换为字符串列表,并将包含字典单词的文本文件转换为单词列表。现在,我需要查看拼写错误列表中的单词是否在字典单词列表中 def spellCheck(): checkFile=input('Enter file name: ') inFile=open(checkFile,'r') # This separates my original tex

我正在编写一个拼写检查函数,我正在使用两个文本文件:一个是拼写错误的文本,另一个是包含字典中一堆单词的文本文件。我已将拼写错误的单词文本转换为字符串列表,并将包含字典单词的文本文件转换为单词列表。现在,我需要查看拼写错误列表中的单词是否在字典单词列表中

def spellCheck():
    checkFile=input('Enter file name: ')
    inFile=open(checkFile,'r')

# This separates my original text file into a list like this
# [['It','was','the','besst','of','times,'],
# ['it','was','teh','worst','of','times']]

    separate=[]
    for line in inFile:
        separate.append(line.split())

# This opens my list of words from the dictionary and 
# turns it into a list of the words.

    wordFile=open('words.txt','r')
    words=wordFile.read()
    wordList=(list(words.split()))
    wordFile.close()


# I need this newList to be a list of the correctly spelled words 
# in my separate[] list and if the word isn't spelled correctly 
# it will go into another if statement... 

    newList=[]
    for word in separate:
        if word in wordList:
            newList.append(word)
    return newList
试试这个:

newList = []
for line in separate:
    for word in line:
        if word in wordList:
            newList.append(word)
return newList
您遇到的问题是,您正在迭代
separate
,这是一个列表列表。您的
单词列表中不存在任何列表,这就是if语句总是失败的原因。要迭代的单词位于
separate
中包含的子列表中。因此,您可以在第二个for循环中迭代这些单词。您还可以对itertools.chain.from\u iterable(separate)
中的单词使用

希望这有帮助

试试这个:

newList = []
for line in separate:
    for word in line:
        if word in wordList:
            newList.append(word)
return newList
您遇到的问题是,您正在迭代
separate
,这是一个列表列表。您的
单词列表中不存在任何列表,这就是if语句总是失败的原因。要迭代的单词位于
separate
中包含的子列表中。因此,您可以在第二个for循环中迭代这些单词。您还可以对itertools.chain.from\u iterable(separate)
中的单词使用


希望这对你有所帮助。首先,谈谈数据结构。您应该使用
set
s,而不是
list
s,因为您(显然)只需要每个单词的副本。您可以从列表中创建集合:

input_words = set(word for line in separate for word in line) # since it is a list of lists
correct_words = set(word_list)
那么,就这么简单:

new_list = input_words.intersection(correct_words)
如果你想要不正确的单词,你可以用另一行:

incorrect = input_words.difference(correct_words)
注意,我使用了带有下划线的名称,而不是PEP 8中推荐的CamelCase。
但是,请记住,这对于拼写检查不是非常有效,因为您不检查上下文。

首先,介绍一下数据结构。您应该使用
set
s,而不是
list
s,因为您(显然)只需要每个单词的副本。您可以从列表中创建集合:

input_words = set(word for line in separate for word in line) # since it is a list of lists
correct_words = set(word_list)
那么,就这么简单:

new_list = input_words.intersection(correct_words)
如果你想要不正确的单词,你可以用另一行:

incorrect = input_words.difference(correct_words)
注意,我使用了带有下划线的名称,而不是PEP 8中推荐的CamelCase。
但是,请记住,这对于拼写检查不是很有效,因为您不检查上下文。

我希望我正确地修复了缩进-您能检查一下吗?我得绕几行…谢谢你!当我运行我的程序时,我得到了一个空列表。你知道我做错了什么吗?你是在问,但现在试图使用列表而不是dict吗?我希望我正确地修复了缩进-你能检查一下吗?我得绕几行…谢谢你!当我运行我的程序时,我得到了一个空列表。你知道我做错了什么吗?你是在问,但现在正试图使用列表而不是
dict