【发布时间】:2013-12-31 19:46:23
【问题描述】:
我正在尝试使用 Python 的子函数,但无法使其正常工作。从我一直在做的故障排除来看,我认为这与字符串中的 unicode 字符有关。
# -*- coding: utf-8 -*-
reload(sys)
sys.setdefaultencoding('utf-8')
import re
someFunction(string):
string = string.decode('utf-8')
match = re.search(ur'éé', string)
if match:
print >> sys.stderr, "It was found"
else:
print >> sys.stderr, "It was NOT found"
if isinstance(string, str):
print >> sys.stderr, 'string is a string object'
elif isinstance(string, unicode):
print >> sys.stderr, 'string is a unicode object'
new_string = re.sub(ur'éé', ur'é:', string)
return new_string
stringNew = 'éégktha'
returnedString = someFunction(stringNew)
print >> sys.stderr, "After printing it: " + returnedString
#At this point in the code string = 'éégktha'
returnString = someFunction(string)
print >> sys.stderr, "After printing it: " + returnedString
所以我想要'é:gktha'。以下是我运行此代码时打印到错误日志的内容。
It was found
string is a unicode object
é:gktha
It was NOT found
string is a unicode object
éégktha
所以我认为它必须是传递给我的函数的字符串。当我将其声明为 unicode 字符串或字符串文字然后对其进行解码时,就会找到该模式。但是在传入的字符串中找不到该模式。我在想我的string = string.decode('utf-8') 语句会转换任何传递给函数的字符串,然后就可以工作了。
我尝试在 python 解释器中执行此操作以解决此问题,当我将字符串声明为 unicode 字符串时,它可以工作。
string = u'éégktha'
所以为了模拟函数,我声明了字符串,然后将其“解码”到,然后尝试了我的正则表达式,它起作用了。
string = 'éégktha'
newString = string.decode('utf8')
string = re.sub(ur'éé', ur'é:', newString)
print string #é:gktha
这个网络应用程序可以处理大量的 unicode 字符。这是 Python 2.5,我在处理 unicode 字符时总是很吃力。非常感谢任何帮助和知识。
【问题讨论】:
-
您粘贴的代码应该可以工作。也许问题不在这里。
-
打印
string传递给函数。 -
更新了问题以显示它在传递给函数之前已被打印。我直接从日志中提取了输出。再次感谢您的帮助。
标签: python regex string unicode python-2.5