Skip to main content
 首页 » 编程设计

python正则表达式替换unicode

2024年11月01日26linjiqin

在第一个测试字符串中,我试图用空格替换文本中间的 Unicode 右箭头字符,但它似乎不起作用。

一般来说,我试图删除所有单个字符或更多 unicode“非单词”,但如果它们是 a-z0-9 和 unicode 的混合或只是\w,则保留单词

# -*- coding: utf-8 -*- 
import re 
str = 'hi… » Test' 
str = 're of… » Pr' 
str = 're of… » Pr | removepipeaswell' 
print str 
str = re.sub(r' [^a-z0-9]+ ', ' ', str , re.UNICODE|re.MULTILINE) 
# str = re.sub(r' [^\p{Alpha}] ', ' ', str, re.UNICODE) 
print str 
're of… Pr removepipeaswell' #expected output 
 
str_nbsp = 'afds » asf' 

编辑:添加了另一个测试字符串,我不想删除“of...”(unicode 点),我只想删除多个 unicode(非单词)字符。

编辑:使用它适用于测试用例,(但不是在完整的 html 中??? - 它似乎只将前半部分的匹配替换为字符串,然后忽略其余部分。)

str = re.sub(r' [^a-z0-9]+ ', ' ', str , re.UNICODE|re.MULTILINE) 

编辑:fml,这一定是一些愚蠢的事情,比如没有正确阅读参数列表:http://bytes.com/topic/python/answers/689341-sub-does-not-replace-all-occurences

[谁刚刚删除了他们的回复 - 感谢您的帮助。]

str = re.sub(r' [^a-z0-9]+ ', ' ', str) 

最终的测试字符串“str_nbsp”与上面的正则表达式不匹配。其中一个空格字符实际上是一个不间断的空格字符。我使用 www.regexr.com 并将鼠标悬停在每个字符上来解决这个问题。

请您参考如下方法:

str = re.sub(r' [^a-z0-9]+ ', ' ', str)