提取搜索词周围的词 [英] Extract words surrounding a search word

查看:107
本文介绍了提取搜索词周围的词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个脚本可以在文本中搜索单词.搜索进行得非常好,结果按预期工作.我要达到的目标是提取匹配附近的n单词.例如:

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.

假设我正在寻找place,我需要提取右侧的3个单词和左侧的3个单词.在这种情况下,它们将是:

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?

谢谢!

推荐答案

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

这篇关于提取搜索词周围的词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆