Skip to main content
 首页 » 编程设计

python之从段落中提取热字符之间的多个字符串

2025年04月02日29傻小

现在我真的找不到标题的方法,但我可以用代码解释我要做什么。

所以我可以接受用户评论并检查它是否具有这些“[[Keyword]]”修饰符。现在我想进一步扩展它以允许多个。

如果用户在当前代码行中输入多个修饰符,就会发生这种情况。

#comment in this case is "I want to [[find]] [[this]] [[Special]] word." 
# c is the comment. 
body = c.body 
# Finds the hot word 
result = re.search("\[\[(.*)\]\]", body, re.IGNORECASE) 
print(result) 

预期结果:

>>>find this Special 

返回结果:

>>>find]] [[this]] [[Special 

有什么办法可以把每个结果都放入某种数组中,这样我就可以测量数组的长度,每个结果都对应一个数字

我希望它如何工作。

print(result[0] +'\n') 
print(result[1] +'\n') 
print(result[2] +'\n') 
>>>find 
>>>this 
>>>Special 

请您参考如下方法:

.* 默认是greedy。您希望它以非贪婪 模式匹配,以便尽可能少地匹配。您可以使用 .*? 而不是 .* 来做到这一点。您还应该使用 re.findall 来获取所有匹配项,而不是 re.search,后者只会返回第一个匹配项。

>>> re.findall(r"\[\[(.*?)\]\]", body, re.IGNORECASE) 
['find', 'this', 'special']