python - 我想在Python 2.7中的长字符串(段落)中提取围绕给定单词的一定数量的单词

标签 python python-2.7 numbers extract words

我正在尝试提取给定单词周围的选定数量的单词。我举个例子来说明这一点:

string =“教育应以人的个性的充分发展为目的,并加强对人权和基本自由的尊重。”

1)所选单词是development,我需要获取它周围的6个单词,并获取:[to, the, full, of, the, human]


2) 但如果所选单词位于开头或第二个位置,我仍然需要获取 6 个单词,例如:

所选单词是 shall ,我应该得到:[Education, be,directed, to , the , full]

我应该使用“re”模块。到目前为止我设法找到的是:

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:]

但它只对我第一种情况有帮助。有人可以帮我解决这个问题吗,我将非常感激。预先感谢您!

最佳答案

这将提取文本中所有出现的目标单词以及上下文:

import re

text = ("Education shall be directed to the full development of the human personality "
        "and to the strengthening of respect for human rights and fundamental freedoms.")

def search(target, text, context=6):
    # It's easier to use re.findall to split the string, 
    # as we get rid of the punctuation
    words = re.findall(r'\w+', text)

    matches = (i for (i,w) in enumerate(words) if w.lower() == target)
    for index in matches:
        if index < context //2:
            yield words[0:context+1]
        elif index > len(words) - context//2 - 1:
            yield words[-(context+1):]
        else:
            yield words[index - context//2:index + context//2 + 1]

print(list(search('the', text)))
# [['be', 'directed', 'to', 'the', 'full', 'development', 'of'], 
#  ['full', 'development', 'of', 'the', 'human', 'personality', 'and'], 
#  ['personality', 'and', 'to', 'the', 'strengthening', 'of', 'respect']]

print(list(search('shall', text)))
# [['Education', 'shall', 'be', 'directed', 'to', 'the', 'full']]

print(list(search('freedoms', text)))
# [['respect', 'for', 'human', 'rights', 'and', 'fundamental', 'freedoms']]

关于python - 我想在Python 2.7中的长字符串(段落)中提取围绕给定单词的一定数量的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43449773/

相关文章:

Python/Pandas : Remove rows with outlying values, 保留所有列

python - 从 Pandas 组中获取最新值(value)

python - ffmpeg 子进程无法在 OS X 上打开

Python神秘地执行其他幻影脚本

python - 如何从 Python 中的字符串中提取数字?

excel - 删除字符串中的点,数字 < 1000 时出现问题

python - Pygame 能在图形方面做哪些 wxPython 做不到的事情?

c - 在 GCC 4.8 上构建 Python (2.7) 模块失败

python - 查找两个多维列表之间的差异

api - 使用 magento API V2 限制结果数量