python - 如何线性搜索和比较两个 .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)
解决方案
使用集差。
"""
---------------------------
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
推荐阅读
- r - 使用R基于向量复制文件
- spring-batch - 如何使用批处理脚本从文本文件中复制特定单词?
- go - 将golang Web应用程序推送到heroku时,构建包不知道请求的文件(go1.13.7.linux-amd64.tar.gz)?
- postgresql - 是否允许使用基本类型的 json(或 jsonb)“创建域”?
- angular - 如何为 Select 组件的项目使用自定义布局?
- sql - 返回表以手动完成的最简单方法
- css - 带有嵌套列和滚动条的引导 flexbox 布局
- c - 将基数排序 uint64_t 代码从 32 MSB 和 48 MSB 推广到 40 MSB 排序位
- objective-c - 在单个 MTLRenderCommandEncoder 中使用多个渲染管道:如何同步 MTLBuffer?
- python - 如何定义方法的返回类型是超类的实现