我正在做一个项目,我必须从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:
重现问题的步骤:
我将用一个对
str.translate
的调用来替换所有这些,因为您只进行单字符到单字符的替换您只需要定义一个
dict
(可以在每次调用str.translate
时重用),将每个字符映射到替换字符。保持不变的字符不需要添加到映射中您还可以使用
str.maketrans
从字符到字符的映射构造适当的转换表相关问题 更多 >
编程相关推荐