我正在尝试对 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)
最佳答案
使用集合差异。
"""
---------------------------
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
关于python - 我如何线性搜索和比较两个 .text 文件以查看它们之间缺少什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53789036/