首页 > 解决方案 > python - 将字符串转换为 unicode 字符串

问题描述

我使用库 unidecode 将重音字符串转换为 ascii 表示的搅拌。

>>> accented_string = u'Málaga'
# accented_string is of type 'unicode'
>>> import unidecode
>>> unidecode.unidecode(accented_string)
>>> Malaga

但问题是我正在从文件中读取字符串,如何将其发送到“unidecode”库。

for name in strings:
   print unidecode.unidecode(u+name) #?????

我摸不着头脑?如果我对其进行编码,那只会给我错误的编码。

标签: pythonpython-2.7unicodeutf

解决方案


我们仍然不知道您的 pandas 列的类型,所以这里有两个 Python 2 版本:

  • 如果strings已经是一个 Unicode 字符串序列 ( type(name)is unicode):

    for name in strings:
        print unidecode.unidecode(name)
    
  • 如果 的元素strings是常规 Python 2 str( type(name)is str):

    for name in strings:
        print unidecode.unidecode(name.decode("utf-8"))
    

如果您的字符串以 UTF-8 编码存储,这将起作用。否则,您必须提供适当的编码,例如"latin-1"等。

在 Python 3 中,第一个版本应该可以工作;在您到达这一点之前,您必须解决您的编码问题,即当您第一次从磁盘读取数据时。


推荐阅读