我正在尝试提取给定单词周围的选定数量的单词。我举个例子来说明这一点:
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/