Unicode中的Unicode到原始字符

时间:2013-06-17 07:54:11

标签: python python-2.7 unicode unicode-string python-unicode

当我使用时,例如,

unicode_string = u"Austro\u002dHungarian_gulden"
unicode_string.encode("ascii", "ignore")

然后它会给出这个输出:'Austro-Hungarian_gulden'

但我使用的是包含以下数据集的txt文件:

Austria\u002dHungary    Austro\u002dHungarian_gulden
Cocos_\u0028Keeling\u0029_Islands   Australian_dollar
El_Salvador Col\u00f3n_\u0028currency\u0029
Faroe_Islands   Faroese_kr\u00f3na
Georgia_\u0028country\u0029 Georgian_lari

我必须使用Python中的正则表达式来处理这些数据,所以我创建了一个如下脚本,但它不能用字符串中的适当字符替换Unicode值。< / p>

同样地

'\u002d' has appropriate character '-'
'\u0028' has appropriate character '('
'\u0029' has appropriate character ')'

处理文本文件的脚本:

import re
import collections

def extract():
    filename = raw_input("Enter file Name:")
    in_file = file(filename,"r")
    out_file = file("Attribute.txt","w+")
    for line in in_file:
        values = line.split("\t")
        if values[1]:
            str1 = ""
            for list in values[1]:
                list = re.sub("[^\Da-z0-9A-Z()]","",list)
                list = list.replace('_',' ')
                out_file.write(list)
                str1 += list
            out_file.write("    ")
        if values[2]:
            str2 = ""
            for list in values[2]:
                list = re.sub("[^\Da-z0-9A-Z\n]"," ",list)
                list = list.replace('"','')
                list = list.replace('_',' ')
                out_file.write(list)
                str2 += list
        s1 = str1.lstrip()
        s1 = str1.rstrip()
        s2 = str2.lstrip()
        s2 = str2.rstrip()
        print s1+s2

给定数据的预期输出为:

Austria-Hungary Austro-Hungarian gulden
Cocos (Keeling) Islands Australian dollar
El Salvador Coln (currency)
FaroeIslands    Faroese krna
Georgia (country)   Georgian lari

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用decode("unicode_escape")将输入转换为Unicode,然后将encode()输出转换为您选择的编码。

>>> r"Austro\u002dHungarian_gulden".decode("unicode_escape")
u'Austro-Hungarian_gulden'