我以前从没和nltk一起工作过。也可能有更好的解决办法。
在我的代码片段中,我只是执行以下操作:将需要检查名为frequencyList.txt的非英语/英语单词的文件读取到名为lines的变量。
然后我打开一个名为eng_words_only.txt的新文件。此文件将只包含英文单词。最初此文件将为空,稍后执行脚本后,此文件将包含frequencyList.txt中存在的所有英语单词
现在对于frequencyList.txt中的每个单词,我检查它是否也存在于wordnet中。
如果这个词存在,那么我将这个词写入eng_words_only.txt文件,否则我什么也不做。请看我使用wordnet只是为了演示。它不包含所有的英语单词!
代码:from nltk.corpus import wordnet
fList = open("frequencyList.txt","r")#Read the file
lines = fList.readlines()
eWords = open("eng_words_only.txt", "a")#Open file for writing
for w in lines:
if not wordnet.synsets(w):#Comparing if word is non-English
print 'not '+w
else:#If word is an English word
print 'yes '+w
eWords.write(w)#Write to file
eWords.close()#Close the file
测试:我首先创建了一个名为frequencyList.txt的文件,其内容如下:cat
meoooow
mouse
执行代码段后,您将在控制台中看到以下输出:not cat
not meoooow
yes mouse
然后将创建一个文件eng_words_only.txt,其中只包含本应属于英语的单词。eng_words_only.txt将只包含mouse个单词。您可能注意到cat是一个英语单词,但它仍然不在eng_words_only.txt文件中。这就是为什么你应该使用一个好的源代码而不是wordnet。
请注意:python脚本文件和frequencyList.txt应该在同一目录中。此外,您可以使用任何要检查/调查的文件,而不是frequencyList.txt。在这种情况下,也不要忘记更改代码段中的文件名。
第二个解决方案:虽然您没有要求,但仍然有其他方法来做这个英语单词测试。
这里是代码:这里wordlist-eng.txt是包含英语单词的文件。你必须保持
wordlist-eng.txt、frequencyList.txt和同一目录中的python脚本。with open("wordlist-eng.txt") as word_file:
english_words = set(word.strip().lower() for word in word_file)
fList = open("frequencyList.txt","r")
lines = fList.readlines()
fList.close()
eWords = open("eng_words_only.txt", "a")
for w in lines:
if w.strip().lower() in english_words:
eWords.write(w)
else: pass
eWords.close()
执行脚本后,eng_words_only.txt将包含frequencyList.txt文件中存在的所有英语单词。
我希望这能有帮助。