gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:46 25 4
gpt4 key购买 nike

我正在编写一个简单的应用程序,我想用其他词替换某些词。我遇到了使用单引号的单词的问题,例如 aren'tain'tisn'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

关于python - 使用 Python 正则表达式处理 Unicode 字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5098151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com