Yon*_*Kit 2 python dictionary replace punctuation
我正在尝试编写一个函数进程(s,d),通过使用字典来替换字符串中的缩写.其中s是字符串输入,d是字典.例如:
>>>d = {'ASAP':'as soon as possible'}
>>>s = "I will do this ASAP. Regards, X"
>>>process(s,d)
>>>"I will do this as soon as possible. Regards, X"
Run Code Online (Sandbox Code Playgroud)
我已经尝试使用split函数来分隔字符串并将每个部分与字典进行比较.
def process(s):
return ''.join(d[ch] if ch in d else ch for ch in s)
Run Code Online (Sandbox Code Playgroud)
但是,它会返回相同的字符串.我怀疑代码不起作用,因为ASAP在原始字符串中完全停止.如果是这样,我如何忽略标点符号并获得ASAP替换?
以下是使用单个正则表达式执行此操作的方法:
In [24]: d = {'ASAP':'as soon as possible', 'AFAIK': 'as far as I know'}
In [25]: s = 'I will do this ASAP, AFAIK. Regards, X'
In [26]: re.sub(r'\b' + '|'.join(d.keys()) + r'\b', lambda m: d[m.group(0)], s)
Out[26]: 'I will do this as soon as possible, as far as I know. Regards, X'
Run Code Online (Sandbox Code Playgroud)
与基于版本的版本不同str.replace(),这会观察到单词边界,因此不会替换碰巧出现在其他单词中间的缩写(例如"fetch"中的"etc").
此外,与目前为止提供的大多数(全部?)其他解决方案不同,它只对输入字符串进行一次迭代,而不管字典中有多少搜索项.