2017-04-17 29 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

相關問題