2017-04-17 72 views
-3

给定一个文本,一个单词和一个区间,以最有效的方式返回包含该区域内的单词的子字符串。这个想法是,当进行查询时,会返回单词ocurr的上下文,类似于Google所做的。Python:给出一个字和一个区间的子字符串

例如:

text = "This is an example of a string" 
word = "example" 
interval = 2 

回报:

"is an example of a" 

谢谢。

+5

您是否尝试过的东西? – Dadep

+0

你能解释一下间隔的大小和预期的输出之间的关系吗?你想把目标词+ - [间隔] - 每边的词作为子串吗? –

+0

间隔是最接近我要返回的单词的字数,并且仅返回该子字符串:[interval] + word + [interval] – Harold

回答

0

林不知道是不是你的问题的最佳解决方案,但..

outer_pattern = '' 
for i in range(interval): 
    outer_pattern += '\w+ ' 

pattern = '{}{} {}'.format(outer_pattern, word, outer_pattern) 
result = [text[match.start():match.end()] for match in re.finditer(pattern, text)] 

结果这里是所有的匹配列表

+0

感谢您的回复。你如何修改正则表达式,以便在间隔中有更少数量的元素能够识别它?例如,如果该单词在字符串的其中一个末尾,我希望它也返回该时间间隔。 – Harold

相关问题