首页 > 解决方案 > 如何线性搜索和比较两个 .txt 文件以查看它们之间缺少什么?

问题描述

我正在尝试对 2 个 .txt 文件进行线性搜索。一个是故事,另一个是字典中故事中的单词。我正在尝试做的是搜索每个文件,然后将每个单词相互比较,如果字典中缺少一个单词,它应该以拼写错误的形式返回并打印出来。搜索对我来说有点混乱,所以任何帮助将不胜感激!我的 while 循环中的代码是我必须使用的唯一示例,我正在尝试修改它以适应我的场景。如果您有其他方法,请告诉我,因为我正在努力掌握线性搜索概念以比较我搜索的内容。

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

def split_line(line):
    return re.findall('[A-Za-z]+(?:\'[A-Za-z]+)?', line)
# --- Read in a file from disk and put it in an array.


dictionary_list = []
alice_list = []

for line in open("dictionary.txt"):
    line = line.strip()
    dictionary_list.append(split_line(line))

for line in open("AliceInWonderLand200.txt"):
    line = line.strip()
    dictionary_list.append(split_line(line))



"""-----Linear Search-----"""
i = 0

while i < len(dictionary_list) and dictionary_list[i] != alice_list:
    i += 1

if i == len(dictionary_list):
    print("The Name is not on the list." + alice_list)
else:
    alice_list.append(i)
    print("The name is at position", i)

标签: pythonalgorithmsearchlinear-search

解决方案


使用集差。

"""
---------------------------
d.txt
---------------------------
alice
wonderland
alice-again
oh-dear-alice
---------------------------
alice.txt
---------------------------
aline
alice
oh-no-alice
---------------------------

"""

dictionary = list(open('d.txt','r'))
dictionary = set([i.strip() for i in dictionary])
#Once you have your list of words
#dictionary = set(get_dict_list())
input_file = list(open('alice.txt','r'))
input_file = set([i.strip() for i in input_file])
#input_file = set(get_story_list())
misspelled_words = input_file - dictionary

推荐阅读