Py学习  »  Python

如何克服regex标志设置(Python)的问题?

Peter.k • 6 年前 • 1976 次点击  

pattern = re.compile(r'\b(' + '|'.join(re.escape(key) for key in abbreviationsDict().keys()) + r')\W', flags=re.I)
        s = pattern.sub(lambda x: abbreviationsDict()[x.group(1)] + ' ', s)

字典的功能是:

def abbreviationsDict():
    return {'ref.': 'reference', 'ref:': 'reference', 'approx.': 'approximately', 'no.': '', 'nos.': ''}

为了这句话 s = "Variation of Condition on planning application Ref: CB/15/03633/FULL dated 30/11/2015: Condition 9" 我得到一个错误:

   s = pattern.sub(lambda x: abbreviationsDict()[x.group(1)] + ' ', s)

KeyError: 'Ref:'

当我小写的时候 s 变量,但我得到小写的结果。这面旗子我做错什么了,所以不能按需使用?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55578
文章 [ 2 ]  |  最新文章 6 年前
Juan C. Roldán
Reply   •   1 楼
Juan C. Roldán    7 年前

re.I 为了使解析器不区分大小写,正则表达式的匹配将与原始大小写一起返回。因此,你需要改变

abbreviationsDict()[x.group(1)]

到

abbreviationsDict()[x.group(1).lower()]
Wiktor Stribiżew
Reply   •   2 楼
Wiktor Stribiżew    7 年前

因为字典中的键是小写的,所以您应该将匹配项转换为小写:

s = pattern.sub(lambda x: abbreviationsDict()[x.group(1).lower()] + ' ', s)
                                                        ^^^^^^^^ 

见 Python demo :

import re
def abbreviationsDict():
    return {'ref.': 'reference', 'ref:': 'reference', 'approx.': 'approximately', 'no.': '', 'nos.': ''}
pattern = re.compile(r'\b({})(?!\w)'.format('|'.join(re.escape(key) for key in abbreviationsDict().keys())), flags=re.I)
s = "Variation of Condition on planning application Ref: CB/15/03633/FULL dated 30/11/2015: Condition 9"
s = pattern.sub(lambda x: abbreviationsDict()[x.group(1).lower()], s)
print(s)
# => Variation of Condition on planning application reference CB/15/03633/FULL dated 30/11/2015: Condition 9

请注意 \W 在模式的末尾,使用任何非单词字符,并用空格替换它。我建议你转身 \西 变成一个 (?!\w) 并放弃附加 " " 在lambda表达式中。