我知道已经有几个关于这个主题的问题,但没有一个可以帮助我解决我的问题。
当 CSV 文档中的名称位于标签 {SPEAKER}
或 {GROUP OF SPEAKERS}
后面时,我必须将其替换。
代码
我的脚本的错误部分是:
list_speakers = re.compile(r'^\{GROUP OF SPEAKERS\}\t(.*)|^\{SPEAKER\}\t(.*)')
usernames = set()
for f in corpus:
with open(f, "r", encoding=encoding) as fin:
line = fin.readline()
while line:
line = line.rstrip()
if not line:
line = fin.readline()
continue
if not list_speakers.match(line):
line = fin.readline()
continue
names = list_speakers.sub(r'\1', line)
names = names.split(", ")
for name in names:
usernames.add(name)
line = fin.readline()
错误
但是,我收到以下错误消息:
File "/usr/lib/python2.7/re.py", line 291, in filter
return sre_parse.expand_template(template, match)
File "/usr/lib/python2.7/sre_parse.py", line 831, in expand_template
raise error, "unmatched group"
sre_constants.error: unmatched group
我使用的是 Python 2.7。
我该如何解决这个问题?
最佳答案
issue is a known one :如果组未初始化,则在 Python 3.5 及以下版本中,反向引用不会设置为空字符串。
您需要确保只有一个或使用 lambda 表达式作为替换参数来实现自定义替换逻辑。
在这里,您可以轻松地将正则表达式修改为具有单个捕获组的模式:
r'^\{(?:GROUP OF SPEAKERS|SPEAKER)\}\t(.*)'
请参阅regex demo
详细信息
^
- 字符串开头\{
- 一个{
(?:GROUP OF SPEAKERS|SPEAKER)
- 匹配GROUP OF SPEAKERS
或SPEAKER
的非捕获组\}
- 一个}
(也可以写}
,不需要转义)\t
- 制表符(.*)
- 第 1 组:除换行符之外的任何 0+ 个字符,尽可能多(该行的其余部分)。
关于python - 使用 Pattern.sub(r'\1' 时出现错误 "sre_constants.error: unmatched group",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379744/