对于编程实验室,我的任务是编写一个程序来检查单词的拼写。我自己这样做所以这基本上是我的最后一招。程序应该像这样工作:迭代你要检查的文档的所有行。如果单词不在字典中,打印单词和行在哪里找到它。
我必须使用一个字典文件,其中所有单词都大写。我正在检查正确拼写的文件 不是。所以在某个地方我必须把这些词大写,但我无法弄清楚在哪里。每次运行此代码时,它只会打印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
答案 0 :(得分:1)
首先,您最好使用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)
希望这有帮助
答案 1 :(得分:0)
您可以小写字典中的单词:
for line in file:
line = line.strip().lower()
dictionary.append(line)
并小写您要检查的单词:
for word in line:
i += 1
word = word.lower()
...