使用线性搜索的Python拼写检查器

2024-04-29 08:23:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图写一个拼写检查使用线性搜索,其中采取莎士比亚的全部作品,并比较它与10000字的字典。我希望代码输出莎士比亚全集中字典中没有的所有单词。我已经附上了我目前的输出以及我要找的输出图片。我目前的代码没有产生任何错误,但从目前的输出显示,在莎士比亚全集所有的话。感谢您的帮助。你知道吗

https://imgur.com/a/Gcmpy:电流输出

https://imgur.com/a/nLWJ8:我要找的输出

import re
import time
start_time = time.time()

def LinearSearch(Target, Words):
#Linear search for target in words. Words need not be sorted.
    for s in Words:
        if s==Target:
            return True
        return False

# Gets the Dictionary.
Words = [s.strip("\n").lower() for s in open("10kWords.txt")]

# Gets ShakespearesFullWorks and Encodes it.
Input_File = open('ShakespeareFullWorks.txt', "r", encoding='utf-8')
lines = Input_File.readlines()
for x in lines:
    if not LinearSearch(x, Words):
        print (re.findall(r"[\w']+", x))

print ("--- %s seconds ---" % (time.time() - start_time))

Tags: 代码inhttpsimportrecomtargetfor
1条回答
网友
1楼 · 发布于 2024-04-29 08:23:32

问题是LinearSearch(x, Words)中的x不是一个单词,而是一行。所以每一行都是打印出来的,因为一行可能与一个单词不匹配。你需要做:

for line in lines:
    for word in re.findall(r"[\w']+", line):
        if not LinearSearch(word, Words):
            print(word)

假设re.findall(r"[\w']+", x)返回x中的单词列表。你知道吗

相关问题 更多 >