簡體   English   中英

如何使用正則表達式從文本中查找特定單詞並返回所有出現的單詞?

[英]How to use regex to find a specific word from text and return all occurences?

就像問題標題一樣。

我是Python和正則表達式的新手。 因此,我必須從段落中搜索特定單詞並顯示所有出現的索引。

例如:

該段是:

這是一個測試文本,用於測試和測試。

和這個詞:

測試

算法應返回上段中3個單詞test的非重疊出現的索引(但不測試 ,因為我的意思是搜索整個單詞,而不僅僅是子字符串)。

另一個帶有相同段落和這個“單詞”的例子:

測試和

該算法應返回2次測試和

我想我必須使用一些正則表達式來找到整個單詞的模式,前后都是標點符號. , ; ? - . , ; ? -

谷歌搜索后我發現應該使用像re.finditer這樣的東西,但似乎我還沒找到正確的方法。 請幫忙,提前謝謝。 ;)

是的, finditer是要走的路。 使用start()查找匹配的索引。


例:

import re

a="This is a testing text and used to test and test and test."
print [m.start() for m in re.finditer(r"\btest\b", a)]
print [m.start() for m in re.finditer(r"\btest and\b", a)]

輸出:

[35,44,53]
[35,44]

在正則表達式中使用單詞邊界錨點\\b表示您希望匹配在單詞邊界處開始/結束。

>>> sentence = "This is a testing text and used to test and test and test."
>>> pattern = re.compile(r'\btest\b')
>>> [m.start() for m in pattern.finditer(sentence)]
[35, 44, 53]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM