【发布时间】:2021-09-15 21:55:52
【问题描述】:
目标
我想得到被特定符号包围的单词,例如括号和它们的索引号。
# input and symbol []
A key word is put in parentheses, like these: [keyword] or [key word]
# output
keyword (9, 9)
key word (11, 12)
索引号被认为遵循拆分输入句子的列表。
问题
目前的输出主要有两个问题。
-
索引计数是由非词库完成的。
-
与正则表达式匹配没有达到我的预期。
输出
['A', 'key', 'word', 'is', 'put', 'in', 'parentheses,', 'like', 'these:', '[keyword]', 'or', '[key', 'word]']
keyword] or [key word
(47, 68)
代码
import re
sentence = "A key word is put in parentheses, like these: [keyword] or [key word]"
splitted = sentence.split(' ')
matched = re.finditer("(?<=\[).*(?=\])", sentence)
print(matched)
for w in matched:
print(w.group())
print(w.span())
如何修复当前代码以提取目标输出?
【问题讨论】:
-
你不需要正则表达式。只需
split()短语并检查元素中是否有[ -
使用这个作为正确的模式:matched = re.finditer("(?
标签: python python-3.x string nsregularexpression