python - 在两个文本文件之间寻找长度 > 4 的匹配字符串
问题描述
我正在尝试读取两个文本文件,然后在每个文件中搜索两者之间共有的字符串,最小长度为 5。
我写的代码:
db = open("list_of_2","r").read()
lp = open("lastpass","r").read()
word = ''
length = 0
for dbchar in db:
for lpchar in lp:
if dbchar == lpchar:
word += str(dbchar)
length += 1
else:
length = 0
word = ''
if length > 4:
print(word)
该代码当前一遍又一遍地打印像'-----'和'55555'这样的字符串,并且似乎没有打破循环(这些特定的字符串只出现lp
一次)。我也不相信它会找到不只是重复相同字符的字符串。
如何将代码更改为:
- 只让它运行并打印每个事件一次,并且
- 不只是找到重复的相同字符的字符串吗?
编辑:这里有一些模拟文本文件。其中,字符串 'ghtyty' 在 file1 中出现了 3 次,在 file2 中出现了 4 次。代码应该打印 'ghtyty' 到控制台一次。
解决方案
我会建议一种不同的方法。将文件拆分为单词并仅保留 5 个字符或更大的单词。使用集合来寻找交叉点——这样会更快。
db_words = set([x for x in db.split() if len(x) > 4])
lp_words = set([x for x in lp.split() if len(x) > 4])
matches = db_words & lp_words
如果要排除所有相同字符的单词,可以像这样定义列表推导:
[x for x in db.split() if len(x) > 4 and x != x[0]*len(x)]
如果您正在寻找任何匹配的连续字符序列,这可能会更好:
i_skip = set() # characters to skip if they are already in a printed word
j_skip = set()
for i in range(len(db)-4):
if i in i_skip: continue
for j in range(len(lp)-4):
if j in j_skip: continue
if db[i] == lp[j]:
word_len = 5
while db[i:i+word_len] == lp[j:j+word_len]:
if db[i:i+word_len+1] == lp[j:j+word_len+1]:
word_len += 1
else:
print(db[i:i+word_len])
i_skip.update(range(i, i+word_len))
j_skip.update(range(j, j+word_len))
break
推荐阅读
- google-apps-script - 使用脚本编辑器将 Excel 文件从 Google Drive 复制到新创建的文件夹
- r - 使用 SLURM bash 脚本进行并行化和资源分配
- flutter - 使用 Positioned 小部件在 ListView.builder 项目小部件上添加小部件
- laravel - 获取徽标以显示在电子邮件标题中
- javascript - 如何在 IE 11 中实现扩展运算符?
- sql - Oracle 中的 IF ELSE 条件需要帮助
- neo4j - Neo4j 通过原生 api 创建索引的问题
- vb.net - 如何进行循环以查找匹配的字符串
- azure - 有没有办法在任务运行时(在完成之前)从 Azue Batch 任务中动态流式传输数据
- c# - 使用模型等待多个调用