1
import time
with open('txt.txt', 'r') as myfile:
    data=myfile.read().replace('\n', '')
pdf_content = data.split(" ")`
vocab = input('Vocab word to search for: ')

if vocab not in pdf_content:
    print('word not found....')
if vocab in pdf_content:
    for vocab in pdf_content:
        print((" ".join(pdf_content[1])))
time.sleep(200)

I want to basically search a body of text for a certain word and return a group of words around that 1 word.

ex. your paragraph is the quick brown fox jumped over the lazy dog and we wanted to search for brown, it would return quick brown fox since those are the surrounding words. I'm not sure how to do this but help would be greatly appreciated

2
  • Formatting done Commented Sep 19, 2018 at 2:02
  • Find index of word and get your required o/p using index-1, index and index+1 Commented Sep 19, 2018 at 2:06

3 Answers 3

3

You could use a regular expression:

import re

text = 'the quick brown fox jumped over the lazy dog'

word = "brown"
for match in re.finditer(r"\w+\W+{}\W+\w+".format(word), text):
    print(match.group())

Output

quick brown fox

Regex

  • \w+ matches a word
  • \W+ followed by one or more characters that are not words
  • followed by the chosen word, in this case 'brown'
Sign up to request clarification or add additional context in comments.

Comments

0

Or a one-liner:

print(' '.join(s.split()[s.split().index(s2)-1:s.split().index(s2)+2]))

Demo:

s = 'the quick brown fox jumped over the lazy dog'
s2 = "brown"
print(' '.join(s.split()[s.split().index(s2)-1:s.split().index(s2)+2]))

Explanation:

  • join the strings of the index-1 to index+1 (+2 in this case)

  • index meaning the index of s2 in the split list from s

Comments

0

Try splitting the words and use indices:

pdf_content = "the quick brown fox jumps over the lazy dog"
word = "brown"

words = pdf_content.split()
pos = words.index(word)
found = word
if pos > 0:
    found = words[pos - 1] + " " + found
if pos < len(words) - 1:
    found = found + " " + words[pos + 1]

print(found)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.