开发者

Matching lines in Python

I need to match some string in a text file and want to get return the matching line. Let's say, I have string in 2D array as follows:

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

So that I can search in a text file for the string e.g.: ['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby']['', ''] ['', ''].... In file.txt the lines look like this:

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.

then I should get return the whole line with marking the matches string. For 1D array the following code works:

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

For the above 2D-array, how to proceed on?


How about this:

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


This should work:

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))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜