dwb
dwb

Reputation: 483

Search a string for a word/sentence and print the following word

I have a string that has around 10 lines of text. What I am trying to do is find a sentence that has a specific word(s) in it, and display the word following.

Example String:

The quick brown fox

The slow donkey

The slobbery dog

The Furry Cat

I want the script to search for 'The slow', then print the following word, so in this case, 'donkey'.

I have tried using the Find function, but that just prints the location of the word(s).

Example code:

 sSearch = output.find("destination-pattern")
        print(sSearch)

Any help would be greatly appreciated.

Upvotes: 0

Views: 599

Answers (4)

accdias
accdias

Reputation: 5372

You can do it using regular expressions:

>>> import re
>>> r=re.compile(r'The slow\s+\b(\w+)\b')
>>> r.match('The slow donkey')[1]
'donkey'
>>> 

Upvotes: 0

Daweo
Daweo

Reputation: 36330

I would do it using regular expressions (re module) following way:

import re
txt = '''The quick brown fox
The slow donkey
The slobbery dog
The Furry Cat'''
words = re.findall(r'(?<=The slow) (\w*)',txt)
print(words) # prints ['donkey']

Note that words is now list of words, if you are sure that there is exactly 1 word to be found you could do then:

word = words[0]
print(word) # prints donkey

Explanation: I used so-called lookbehind assertion in first argument of re.findall, which mean I am looking for something behind The slow. \w* means any substring consisting of: letters, digits, underscores (_). I enclosed it in group (brackets) because it is not part of word.

Upvotes: 0

Uli Sotschok
Uli Sotschok

Reputation: 1236

You could work with regular expressions. Python has builtin library called re.

Example usage:

s = "The slow donkey some more text"
finder = "The slow"
idx_finder_end = s.find(finder) + len(finder)
next_word_match = re.match(r"\s\w*\s", s[idx_finder_end:])
next_word = next_word_match.group().strip()
# donkey

Upvotes: 0

ncica
ncica

Reputation: 7206

output = "The slow donkey brown fox"
patt = "The slow"
sSearch = output.find(patt)
print(output[sSearch+len(patt)+1:].split(' ')[0])

output:

donkey

Upvotes: 1

Related Questions