首页 > 解决方案 > 在两个文本文件之间寻找长度 > 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一次)。我也不相信它会找到只是重复相同字符的字符串。

如何将代码更改为:

  1. 只让它运行并打印每个事件一次,并且
  2. 不只是找到重复的相同字符的字符串吗?

编辑:这里有一些模拟文本文件。其中,字符串 'ghtyty' 在 file1 中出现了 3 次,在 file2 中出现了 4 次。代码应该打印 'ghtyty' 到控制台一次。

文件1 文件 2

标签: python

解决方案


我会建议一种不同的方法。将文件拆分为单词并仅保留 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

推荐阅读