为什么re.sub()在Python3.6中不起作用?

2024-09-28 22:23:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个项目,我必须从Excel电子表格中读取数据。我正在使用Python

我注意到,当我使用“re.sub()”时,原始字符串中的字符没有被替换。当我使用“string.replace()”时,原始字符串中的字符会被替换,但当我使用“re.sub()”时不会被替换

我想知道我是否做错了什么。 有人能帮你查一下吗

技术细节:

这就是我最初拥有的:

string = re.sub(u'([\u2000-\u206f])', " ", string)
string = re.sub(u'(\u00a0)', " ", string)

string = string.replace("‰", " ") #\u0089
string = string.replace("¤", " ") #\u00a4

根据“切普纳”的建议,我将逻辑更改为:

replacementDict = {}
replacementDict.update(dict.fromkeys(map(chr, range(0x2000, 0x206f)), " "))
replacementDict['\u00a0'] = " "
replacementDict['\u0089'] = " "
replacementDict['\u00a4'] = " "

string = string.translate(replacementDict)

但是我仍然无法从字符串中删除非法字符

您可以下载脚本和示例测试here

重现问题的步骤:

  • 按原样运行脚本(不需要向脚本发送参数),您会注意到不匹配的行是带有非法字符的行

Tags: 项目字符串re脚本string读取数据字符excel
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:58

我将用一个对str.translate的调用来替换所有这些,因为您只进行单字符到单字符的替换

您只需要定义一个dict(可以在每次调用str.translate时重用),将每个字符映射到替换字符。保持不变的字符不需要添加到映射中

replacements = {}
replacements.update(dict.fromkeys(range(0x2000, 0x2070), " "))
replacements[0x1680] = ' '
# etc

string = string.translate(replacements)

您还可以使用str.maketrans从字符到字符的映射构造适当的转换表

相关问题 更多 >