0

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?

Liza
  • 11
  • 1
  • possible duplicate of [How to find the select the whole line for looking for only substring from the line in Python](http://stackoverflow.com/questions/6419711/how-to-find-the-select-the-whole-line-for-looking-for-only-substring-from-the-lin) – Björn Pollex Jun 30 '11 at 17:43
  • I'm rather perplexed by your Sentence "For 1D array the following code works: [CODE] For the uppercase, how to proceed on..." Are you stating that it works for when there's uppercase portions, should the output be in uppercase, please further define. – Jeff Langemeier Jun 30 '11 at 17:45
  • **@Jeff Langemeier** I just want to return those line that match both array(ignoring case). – Liza Jun 30 '11 at 17:51

2 Answers2

2

How about this:

def search(sentences, words):
  return [s for s in sentences if all([w in s for w in words])]
g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
1

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))
Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • **@Space_C0wb0y** if I want to search for all string, let's say for here `matched = list(search(['Shoo-Be-Doo-Be-Doo-Da-Day', 'Henry Cosby'],sentences))` a number of string , I will take from another string.txt file, then how to proceed..Thanks in advance! – Liza Jun 30 '11 at 18:05
  • @Liza: I am unsure what you mean. If you want to match one of multiple patterns, see my updated answer. Also, you don't need to write our usernames bold. Just `@username` will suffice. – Björn Pollex Jun 30 '11 at 18:09