【发布时间】:2014-02-13 23:18:20
【问题描述】:
我需要根据一组自定义替换替换 unicode。自定义替换是由其他人的 API 定义的,我基本上只需要处理它。就目前而言,我已将所有必需的替换提取到一个 csv 文件中。这是一个示例:
\u0020,
\u0021,!
\u0023,#
\u0024,$
\u0025,%
\u0026,&
\u0028,(
\u0029,)
\u002a,*
\u002b,+
\u002c,","
\u002d,-
\u002e,.
\u002f,/
\u03ba,kappa
...
我通过破解 API 所有者在需要进行转换时为自己使用的 java 程序在 MS Excel 中生成了这个(不......当 API 接收到输入时,他们不会只运行转换器......) .定义了约 1500 个替换。
当我生成输出(从我的 Django 应用程序)作为输入发送到他们的 API 时,我想处理替换。这是我一直在尝试的方法:
class UTF8Converter(object):
def __init__(self):
#create replacement mapper
full_file_path = os.path.join(os.path.dirname(__file__),
CONVERSION_FILE)
with open(full_file_path) as csvfile:
reader = csv.reader(csvfile)
mapping = []
for row in reader:
#remove escape-y slash
mapping.append( (row[0], row[1]) ) # here's the problem
self.mapping = mapping
def replace_UTF8(self, string):
for old, new in self.mapping:
print new
string.replace(old, new)
return string
问题在于 csv 文件中的 unicode 代码显示为,例如, self.mapping[example][0] = '\\u00e0'。好吧,那就错了,让我们试试吧:
mapping.append( (row[0].decode("string_escape"), row[1]) )
没有变化。怎么样:
mapping.append( (row[0].decode("unicode_escape"), row[1]) )
好的,现在self.mapping[example][0] = u'\xe0'。所以是的,这就是我需要替换的字符......但是我需要调用 replace_UTF8() 函数的字符串看起来像u'\u00e0'。
我也试过row[0].decode("utf-8")、row[0].encode("utf-8")、unicode(row[0], "utf-8")。
我也尝试过this,但我在 csv 文件中没有 unicode 字符,我有 unicode 代码点(不确定这是否是正确的术语或什么)。
那么,如何将我从 csv 文件中读取的字符串转换为可以与 mythingthatneedsconverted.replace(...) 一起使用的 unicode 字符串?
或者...我是否需要对 csv 文件执行其他操作才能使用更明智的方法?
【问题讨论】:
-
附带说明一下,您为什么要使用翻译列表并遍历整个列表来调用
replace,而不是仅仅构建一个表以与unicode.translate一起使用? -
另外,
string.replace(old, new)只是返回一个新字符串,它不会以任何方式改变string。此外,您无法在 UTF-8 数据中搜索 Unicode 字符串,您必须将其解码为 Unicode,然后在那里进行工作。