[英]Extract words from sentence that are containing substring
我想提取包含特定 substring 的完整短語(一個或多個單詞)。Substring 可以有一個多個單詞,substring 中的單詞可以在 test_string 中“中斷”/“拆分”單詞,但所需的test_string
是完整的短語/單詞來自test_string
,例如
test_string = 'this is an example of the text that I have, and I want to by amplifier and lamp'
substring1 = 'he text th'
substring2 = 'amp'
if substring1 in test_string:
print("substring1 found")
if substring2 in test_string:
print("substring2 found")
我想要的 output 是:
[the text that]
[example, amplifier, lamp]
供參考
Substring 可以在單詞的開頭,中間或結尾......沒關系。
這是正則表達式的工作,您可以這樣做:
import re
substring2 = 'amp'
test_string = 'this is an example of the text that I have'
print("matches for substring 1:",re.findall(r"(\w+he text th\w+)", test_string))
print("matches for substring 2:",re.findall(r"(\w+amp\w+)",test_string))
Output:
matches for substring 1:['the text that']
matches for substring 2:['example']
如果你想要一些強大的東西,我會做這樣的事情:
re.findall(r"((?:\w+)?" + re.escape(substring2) + r"(?:\w+)?)", test_string)
這樣你就可以在 substring 中擁有任何你想要的東西。
正則表達式的解釋:
'(?:\w+)' Non capturing group
'?' zero or one
我在 substring 的開頭和結尾都這樣做了,因為它可以是缺失部分的開頭或結尾
import re
test_string = 'this is an example of the text that I have, and I want to by amplifier and lamp'
substrings = ['he text th', 'amp']
for substring in substrings:
print(re.findall(rf'\s(\w*{substring}\w*)\s', test_string))
OUTPUT:
['the text that']
['example', 'amplifier']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.