Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用python在文本中找到关键字后提取几个before单词_Python_Nlp_N Gram - Fatal编程技术网

如何使用python在文本中找到关键字后提取几个before单词

如何使用python在文本中找到关键字后提取几个before单词,python,nlp,n-gram,Python,Nlp,N Gram,我有一个关键字“大师”,我在巨大的文本中搜索关键字。我需要提取关键字的前5个单词和后5个单词(根据它可能会转到下一个/前一个句子的位置),并且这个关键字在巨大的文本中多次出现 首先,我尝试使用text.find(),在文本中查找关键字的位置,并在4个不同的位置找到关键字 >>positions >>[125, 567,34445, 98885445] 所以试着根据空格分割文本,并取前5个单词 text[positions[i]:].split([len(keyword

我有一个关键字“大师”,我在巨大的文本中搜索关键字。我需要提取关键字的前5个单词和后5个单词(根据它可能会转到下一个/前一个句子的位置),并且这个关键字在巨大的文本中多次出现

首先,我尝试使用
text.find()
,在文本中查找关键字的位置,并在4个不同的位置找到关键字

>>positions
>>[125, 567,34445, 98885445] 
所以试着根据空格分割文本,并取前5个单词

text[positions[i]:].split([len(keyword.split()):len(keyword.split())+5]
但是如何提取该关键字之前的5个单词呢?

您只需使用

text[:position[i]].split()[-5:]
为此使用模块。对于第一个关键字匹配:

pattern = "(.+) (.+) (.+) (.+) (.+) grand master (.+) (.+) (.+) (.+) (.+)"
match = re.search(pattern, text)
if match:
    firstword_before = match.group(1) # first pair of parentheses
    lastword_before = match.group(5)

    firstword_after = match.group(6)
    lastword_after = match.group(10)
模式中的括号表示组号。第一对括号对应match.group(1),第二对括号对应match.group(2),依此类推。如果您想要所有可以使用的组:

match.groups() # returns tuple of groups

对于文本中的所有关键字匹配,请使用re.findall。阅读 详情请参阅

还有更好的方法来编写模式。那只是我的懒惰

match.group(0) # returns string of groups