提取搜索词之前和之后的词

时间:2018-02-08 07:05:50

标签: regex

假设我有如下文字。

  

纽约市经常叫纽约市,或者简称纽约市   美国人口最多的城市。估计   人口8537673分布在土地面积约3026   平方英里(784平方公里)纽约市也是最密集的   人口稠密的美国主要城市。

我想找到搜索词出现之前和之后的n个单词。例如,n = 3且搜索项="纽约",则

第一次出现:

  • 之前的词= {The,city,of}
  • 以下单词= {经常,被称为,新}}

第二次出现:

  • 之前的词= {York,经常,被称为}
  • 以下单词= {City,或简称}

第三次发生:

  • 之前的词= {城市,或简称}
  • 以下单词= {is,the,most}

第4次出现:

  • 前面的单词= {miles,784,km2}
  • 以下单词= {City,is,also}

如何使用正则表达式执行此操作?我在Extract words surrounding a search word找到了类似的问题,但它没有考虑多次出现的搜索字词。

尝试:

def search(text,n): 
word = r"\W*([\w]+)" 
groups = re.search(r'{}\W*{}{}'.format(wordn,'place',wordn), text).groups() return groups[:n],groups[n:]

2 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

((?:\w+\W+){3})(?=New York((?:\W+\w+){3}))

并在第1组和第2组中获取您的值

示例来源(run here

import re
regex = r"((?:\w+\W+){3})(?=New York((?:\W+\w+){3}))"

test_str = "The City of New York often called New York City or simply New York is the most populous city in the United States. With an estimated 2016 population of 8537673 distributed over a land area of about 3026 square miles (784 km2) New York City is also the most densely populated major city in the United States."
matches = re.finditer(regex, test_str)

for match in matches:
    print(re.sub(r'\W+', ' ', match.group(1))+"  <------>" +re.sub(r'\W+', ' ', match.group(2)))

Regex 101 Demo

答案 1 :(得分:1)

您需要使用positive lookahead assertion来处理重叠匹配:

re.findall(r"((?:\w+\W+){3})(?=New York((?:\W+\w+){3}))", t)

结果:

[('The City of ', ' often called New'),
 ('York often called ', ' City or simply'),
 ('City or simply ', ' is the most'),
 ('miles (784 km2) ', ' City is also')]