在Python中匹配行

时间:2011-06-30 17:32:55

标签: python string-matching

我需要在文本文件中匹配一些字符串,并希望返回匹配的行。比方说,我在2D数组中有如下字符串:

[['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
 ['My Cherie Amour (song)', 'Stevie Wonder'],
 ["Signed, Sealed, Delivered I'm Yours", 'Stevie Wonder]]

这样我就可以在文本文件中搜索字符串,例如:['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'] ['',''] ['',''] ....在file.txt中,这些行看起来像这样:

abcd Shoo-Be-Doo-Be-Doo-Da-Day skakk gkdka kkhhf Henry Cosby.
gfigka Stevie Wonder hfkhf hghhg fghh My Cherie Amour.
fhsgs hlghhg  Henry Cosby Shoo-Be-Doo-Be-Doo-Da-Day gkgkl.

然后我应该用标记匹配字符串返回整行。 对于1D阵列,以下代码有效:

def search(word, sentences):
    return[i for i in sentences if word in i]

对于上面的2D阵列,如何继续?

2 个答案:

答案 0 :(得分:2)

这个怎么样:

def search(sentences, words):
  return [s for s in sentences if all([w in s for w in words])]

答案 1 :(得分:1)

这应该有效:

def search(patterns, sentences):
    for sentence in sentences:
        if any(all(p in sentence for p in pattern) for pattern in patterns):
            yield sentence

matched = list(search(['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],
                      sentences))