Python检查两个列表中字符串的部分匹配

2024-05-14 21:00:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个列表,如下所示:

c = ['John', 'query 989877 forcast', 'Tamm']
isl = ['My name is Anne Query 989877', 'John', 'Tamm Ju']

我想检查isl中的每一项与c中的每一项,这样我就得到了所有的部分字符串匹配。 我需要的输出如下所示:

^{pr2}$

可以看出,我也得到了部分字符串匹配。在

我试过以下方法:

 out = []
 for word in c:
    for w in isl:
        if word.lower() in w.lower():
                 out.append(word)

但这只给我的输出是

out = ["John", "Tamm"]

我也尝试了以下方法:

print [word for word in c if word.lower() in (e.lower() for e in isl)]

但这只输出“John”。 我怎样才能得到我想要的?在


Tags: 方法字符串in列表forifmyout
2条回答

好吧,我想到了这个!一种非常老套的方法;我自己不喜欢这种方法,但它给了我输出:

Step1:
in: c1 = []
    for r in c:
       c1.append(r.split()) 
out: c1 = [['John'], ['query', '989877', 'forcast'], ['Tamm']]


Step2:
in: p = []
    for w in isl:
        for word in c1:
            for w1 in word:
                 if w1.lower() in w.lower():
                         p.append(w1)
out: p = ['query', '989877', 'John', 'Tamm']


Step3:
in: out = []
    for word in c:
        t = []
        for i in p:
             if i in word:
                t.append(i)
        out.append(t)
out: out = [['John'], ['query', '989877'], ['Tamm']]

Step4:
in: out_final = []
    for i in out:
        out_final.append(" ".join(e for e in i))
out: out_final = ['John', 'query 989877', 'Tamm']

也许是这样的:

def get_sub_strings(s):
    words = s.split()
    for i in xrange(1, len(words)+1):      #reverse the order here
        for n in xrange(0, len(words)+1-i):
            yield ' '.join(words[n:n+i])
...             
>>> out = []
>>> for word in c:
    for sub in get_sub_strings(word.lower()):
        for s in isl:
            if sub in s.lower():
                out.append(sub)
...                 
>>> out
['john', 'query', '989877', 'query 989877', 'tamm']

如果只想存储最大的匹配项,则需要以相反的顺序生成子字符串,并在^{中找到匹配项时立即中断:

^{pr2}$

相关问题 更多 >

    热门问题