Skip to main content
 首页 » 编程设计

python之使用 Python 正则表达式处理 Unicode 字符

2024年09月03日26mate10pro

我正在编写一个简单的应用程序,我想用其他词替换某些词。我遇到了使用单引号的单词的问题,例如 aren't、ain't、isn't。

我有一个包含以下内容的文本文件

aren’t=ain’t 
hello=hey 

我解析文本文件并从中创建字典

u'aren\u2019t' = u'ain\u2019t' 
u'hello' = u'hey' 

然后我尝试替换给定文本中的所有字符

text = u"aren't" 
 
def replace_all(text, dict): 
    for i, k in dict.iteritems(): 
        #replace all whole words of I with K in lower cased text, regex = \bSTRING\b 
        text = re.sub(r"\b" + i + r"\b", k , text.lower()) 
    return text 

问题是 re.sub() 不匹配 u'aren\u2019t' 和 u"aren't"。

我该怎么做才能使我的 replace_all() 函数匹配 "hello" 和 `"aren't"并将它们替换为适当的文本?我可以在 Python 中做一些事情以使我的字典不包含 Unicode 吗?我能否将我的文本转换为使用 Unicode 字符,或者我是否可以修改正则表达式以匹配 Unicode 字符以及所有其他文本?

请您参考如下方法:

我猜你的问题是:

text = u"aren't" 

代替:

text = u"aren’t" 

(注意不同的撇号?)

这是您修改后的代码以使其工作:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
 
import re 
 
d = { 
    u'aren’t': u'ain’t', 
    u'hello': u'hey' 
    } 
#text = u"aren't" 
text = u"aren’t" 
 
 
def replace_all(text, d): 
    for i, k in d.iteritems(): 
        #replace all whole words of I with K in lower cased text, regex = \bSTRING\b 
        text = re.sub(r"\b" + i + r"\b", k , text.lower()) 
    return text 
 
if __name__ == '__main__': 
    newtext = replace_all(text, d) 
    print newtext 

输出:

ain’t