python – 替换正则表达式中的字符

使用Python,我有以下字符串:

['taxes.............................       .7        21.4    (6.2)','regulatory and other matters..................$  39.9        61.5        41.1','Producer contract reformation cost recoveries............................   DASH        26.3        28.3']

我需要用空格替换每个点,而不是数字中的句点.所以结果应该是这样的:

['taxes                                    .7        21.4    (6.2)','regulatory and other matters                  $  39.9        61.5        41.1','Producer contract reformation cost recoveries                               DASH        26.3        28.3']

我尝试过以下方法:

dots=re.compile('(\.{2,})(\s*?[\d\(\$]|\s*?DASH|\s*.)')
newlist=[]
for each in list:
    newline=dots.sub(r'\2'.replace('.',' '),each)
    newdoc.append(newline)

但是,此代码不保留空白区域.谢谢!

解决方法:

在re.sub中使用negative lookarounds

>>> import re
>>> s = ['taxes.............................       .7        21.4    (6.2)','regulatory and other matters..................$  39.9        61.5        41.1','Producer contract reformation cost recoveries............................   DASH        26.3        28.3']
>>> [re.sub(r'(?<!\d)\.(?!\d)', ' ', i) for i in s]
['taxes                                    .7        21.4    (6.2)', 'regulatory and other matters                  $  39.9        61.5        41.1', 'Producer contract reformation cost recoveries                               DASH        26.3        28.3']
上一篇:only_full_group_by


下一篇:python – 用sympy缓慢替换符号矩阵