1

对于编程实验室,我的任务是编写一个检查单词拼写的程序。我自己做这一切,所以这基本上是我最后的手段。程序应该像这样工作:遍历要检查的文档的所有行。如果字典中没有单词,打印单词和行你在哪里找到它。

我必须使用所有单词都大写的字典文件。我正在检查拼写正确的文件不是。所以在某个地方我必须把这些词大写,但我不知道在哪里。每次我运行这段代码时,它只会打印 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

4

2 回答 2

1

首先,您最好使用 aset来保存您的字典单词,以提高查找速度。此外,将字典中的所有单词小写以使比较更加统一会有所帮助。

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)

希望这可以帮助

于 2013-07-16T19:02:14.853 回答
0

您可以将字典中的单词小写:

for line in file:
    line = line.strip().lower()
    dictionary.append(line)

并将您要检查的单词小写:

for word in line:
    i += 1
    word = word.lower()
    ...
于 2013-07-16T18:55:31.823 回答