在Python中查找拼写错误的线性搜索

2024-04-26 02:36:13 发布

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

我正在用程序街机游戏学习Python,我被困在一个实验室里。你知道吗

我应该比较一个文本文件(http://programarcadegames.com/python_examples/en/AliceInWonderLand200.txt)中的每个单词,看看它是否在字典文件(http://programarcadegames.com/python_examples/en/dictionary.txt)中,如果不在,就把它打印出来。我应该用线性搜索。你知道吗

问题是,即使我知道的单词不在字典文件中,也不会被打印出来。任何帮助都将不胜感激。你知道吗

我的代码如下:

# Imports regular expressions
import re

# This function takes a line of text and returns
# a list of words in the line


def split_line(line):
    split = re.findall('[A-Za-z]+(?:\'\"[A-Za-z]+)?', line)
    return split


# Opens the dictionary text file and adds each line to an array, then closes the file
dictionary = open("dictionary.txt")
dict_array = []
for item in dictionary:
    dict_array.append(split_line(item))
print(dict_array)
dictionary.close()

print("---Linear Search---")

# Opens the text for the first chapter of Alice in Wonderland
chapter_1 = open("AliceInWonderland200.txt")

# Breaks down the text by line
for each_line in chapter_1:
    # Breaks down each line to a single word
    words = split_line(each_line)
    # Checks each word against the dictionary array
    for each_word in words:
        i = 0
        # Continues as long as there are more words in the dictionary and no match
        while i < len(dict_array) and each_word.upper() != dict_array[i]:
            i += 1
        # if no match was found print the word being checked
        if not i <= len(dict_array):
            print(each_word)

# Closes the first chapter file
chapter_1.close()

Tags: andthetextintxtfordictionaryline
1条回答
网友
1楼 · 发布于 2024-04-26 02:36:13

Linear search to find spelling errors in Python

像这样的事情应该做(伪代码)

sampleDict = {}
For each word in AliceInWonderLand200.txt:
    sampleDict[word] = True

actualWords = {}
For each word in dictionary.txt:
    actualWords[word] = True

For each word in sampleDict:
    if not (word in actualDict):
        # Oh no!  word isn't in the dictionary

set可能比dict更合适,因为示例中字典的值并不重要。不过,这会让你走的

相关问题 更多 >