对于一个编程实验室,我的任务是编写一个检查单词拼写的程序。我自己做这一切,所以这基本上是我最后的手段。程序应该像这样工作:遍历要检查的文档的所有行。如果字典中没有单词,则打印单词和行你在哪里找到它的。
我必须使用所有单词都大写的字典文件。我正在检查拼写是否正确的文件 不是。所以在某个地方我必须把这些词大写,但我不知道在哪里。每次我运行这段代码时,它只会打印 AliceInWonderLand200.txt 中的每一行。
我的代码:
import re
def split_line(line):
return re.findall('[A-Za-z]+9(?:\'[A-Za-z]+)',line)
file = open("dictionary.txt")
dictionary = []
for line in file:
line = line.strip()
dictionary.append(line)
file.close()
print("----Linear search-----")
file2 = open("AliceInWonderLand200.txt")
i = 0
for line in file2:
words = []
words.append(split_line(line))
for word in line:
i+= 1
word = word.upper()
if word not in dictionary:
print("Line ",i,": probably misspelled: ", word)
file.close()
我尝试过的:
我尝试过使用 words.append(split_line(line.upper()),但那没有用。我试图将 word 分配给 word.upper(),这也没有用。每次当我运行这段代码时,它只会打印 AliceInWonderLand200.txt 中的每一行。
我到处寻找满意的答案。我在 stackoverflow 上发现了同样的问题,但我并没有真正理解答案 Python Spell Checker Linear Search
编辑
我已经添加了我应该让你们更容易的任务和输出。
我的输出应该是什么:
--- Linear Search ---
Line 3 possible misspelled word: Lewis
Line 3 possible misspelled word: Carroll
Line 46 possible misspelled word: labelled
Line 46 possible misspelled word: MARMALADE
Line 58 possible misspelled word: centre
Line 59 possible misspelled word: learnt
Line 69 possible misspelled word: Antipathies
Line 73 possible misspelled word: curtsey
Line 73 possible misspelled word: CURTSEYING
Line 79 possible misspelled word: Dinah'll
Line 80 possible misspelled word: Dinah
Line 81 possible misspelled word: Dinah
Line 89 possible misspelled word: Dinah
Line 89 possible misspelled word: Dinah
Line 149 possible misspelled word: flavour
Line 150 possible misspelled word: toffee
Line 186 possible misspelled word: croquet
任务: http://programarcadegames.com/index.php?chapter=lab_spell_check
最佳答案
首先,您最好使用 set
来保存字典中的单词,以提高查找速度。此外,将字典中的所有单词小写有助于比较更统一。
with open('dictionary.txt') as infile:
dictionary = {line.strip().lower() for line in infile}
print("----Linear search-----")
with open('AliceInWonderLand200.txt') as infile:
for i,line in enumerate(infile, 1):
line = line.strip()
words = split_line(line) # your split_line function
for word in words:
if word.lower() not in dictionary:
print("Line ", i, ": probably misspelled: ", word)
希望对你有帮助
关于algorithm - 我的拼写检查器无法正确比较单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17684708/