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

标签 python python-3.x

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

所以我可以接受用户评论并检查它是否具有这些“[[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']

关于python - 从段落中提取热字符之间的多个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37847967/

相关文章:

python - NumPy 数组元素的自定义排列

python - 尝试在 Python 中创建异常

python - 如何纠正python错误: "icon object is not callable"?

python - 一页上的多个表单 Python FLASK

python - 将 .csv 文件从 URL 读取到 Python 3.x - _csv.Error : iterator should return strings, not bytes(您是否以文本模式打开文件?)

python - 如何将列表元素转换为 int 并与数字进行比较?

python-3.x - 如何向pytest的request.addfinalizer()中传递的函数添加参数?

python - 无法将 PostgreSQL 数据库从 docker 连接到 python

python - 从包含字典的单个变量中创建 Pandas 的数据框

python - 使用scrapy从阿里巴巴抓取标题