Вопрос

I have this script that does a word search in text. The search goes pretty good and results work as expected. What I'm trying to achieve is extract n words close to the match. For example:

The world is a small place, we should try to take care of it.

Suppose I'm looking for place and I need to extract the 3 words on the right and the 3 words on the left. In this case they would be:

left -> [is, a, small]
right -> [we, should, try]

What is the best approach to do this?

Thanks!

Это было полезно?

Решение

def search(text,n):
    '''Searches for text, and retrieves n words either side of the text, which are retuned seperatly'''
    word = r"\W*([\w]+)"
    groups = re.search(r'{}\W*{}{}'.format(word*n,'place',word*n), text).groups()
    return groups[:n],groups[n:]

This allows you to specify how many words either side you want to capture. It works by constructing the regular expression dynamically. With

t = "The world is a small place, we should try to take care of it."
search(t,3)
(('is', 'a', 'small'), ('we', 'should', 'try'))

Другие советы

While regex would work, I think it's overkill for this problem. You're better off with two list comprehensions:

sentence = 'The world is a small place, we should try to take care of it.'.split()
indices = (i for i,word in enumerate(sentence) if word=="place")
neighbors = []
for ind in indices:
    neighbors.append(sentence[ind-3:ind]+sentence[ind+1:ind+4])

Note that if the word that you're looking for appears multiple times consecutively in the sentence, then this algorithm will include the consecutive occurrences as neighbors.
For example:

In [29]: neighbors = []

In [30]: sentence = 'The world is a small place place place, we should try to take care of it.'.split()

In [31]: sentence Out[31]: ['The', 'world', 'is', 'a', 'small', 'place', 'place', 'place,', 'we', 'should', 'try', 'to', 'take', 'care', 'of', 'it.']

In [32]: indices = [i for i,word in enumerate(sentence) if word == 'place']

In [33]: for ind in indices:
   ....:     neighbors.append(sentence[ind-3:ind]+sentence[ind+1:ind+4])


In [34]: neighbors
Out[34]: 
[['is', 'a', 'small', 'place', 'place,', 'we'],
 ['a', 'small', 'place', 'place,', 'we', 'should']]
import re
s='The world is a small place, we should try to take care of it.'
m = re.search(r'((?:\w+\W+){,3})(place)\W+((?:\w+\W+){,3})', s)
if m:
    l = [ x.strip().split() for x in m.groups()]
left, right = l[0], l[2]
print left, right

Output

['is', 'a', 'small'] ['we', 'should', 'try']

If you search for The, it yields:

[] ['world', 'is', 'a']

Handling the scenario where the search keyword appears multiple times. For example below is the input text where search keyword : place appears 3 times

The world is a small place, we should try to take care of this small place by planting trees in every place wherever is possible

Here is the function

import re

def extract_surround_words(text, keyword, n):
    '''
    text : input text
    keyword : the search keyword we are looking
    n : number of words around the keyword
    '''
    #extracting all the words from text
    words = words = re.findall(r'\w+', text)
    
    #iterate through all the words
    for index, word in enumerate(words):

        #check if search keyword matches
        if word == keyword:
            #fetch left side words
            left_side_words = words[index-n : index]
            
            #fetch right side words
            right_side_words = words[index+1 : index + n + 1]
            
            print(left_side_words, right_side_words)

Calling the function

text = 'The world is a small place, we should try to take care of this small place by planting trees in every place wherever is possible'
keyword = "place"
n = 3
extract_surround_words(text, keyword, n)

output : 
['is', 'a', 'small'] ['we', 'should', 'try']
['we', 'should', 'try'] ['to', 'microsot', 'is']
['also', 'take', 'care'] ['googe', 'is', 'one']

Find all of the words:

import re

sentence = 'The world is a small place, we should try to take care of it.'
words = re.findall(r'\w+', sentence)

Get the index of the word that you're looking for:

index = words.index('place')

And then use slicing to find the other ones:

left = words[index - 3:index]
right = words[index + 1:index + 4]
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top