将带有 u'...' 的字符串列表转换为普通字符串列表

Converting list of strings with u'...' to a list of normal strings

我是 python 的新手。并为一个非常基本的问题道歉。

我正在使用 python pattern.en 库并尝试获取单词的同义词。这是我的代码,运行良好。

from pattern.en import wordnet
a=wordnet.synsets('human')
print a[0].synonyms

这是我从中得到的输出:

[u'homo', u'man', u'human being', u'human']

但是对于我的程序,我需要插入这个数组:

['homo', 'man', 'human being', 'human']

如何获得上述输出并从我的输出中删除 'u'。

提前致谢..!

尝试适当的 encoding- 但注意这个 u 对数据没有任何影响- 它只是 unicode 对象的显式表示(不是字节数组),如果你的代码需要返回 unicode 那么最好给它 unicode。

>>>d =  [u'homo', u'man', u'human being', u'human']
>>>print [i.encode('utf-8') for i in d]
>>>['homo', 'man', 'human being', 'human']

简而言之:

无需将 unicode 列表转换为字符串。它们是同一回事


长:

字符串对象中的u'...'前缀表示Python2.0引入的Unicode对象,参见https://docs.python.org/2/tutorial/introduction.html#unicode-strings

Starting with Python 2.0 a new data type for storing text data is available to the programmer: the Unicode object. It can be used to store and manipulate Unicode data (see http://www.unicode.org/) and integrates well with the existing string objects, providing auto-conversions where necessary.

自 Python 3.0 起,参见 https://docs.python.org/3.2/tutorial/introduction.html#about-unicode:

Starting with Python 3.0 all strings support Unicode (see http://www.unicode.org/).

无论默认字符串类型是什么,在检查等价性时,它们在 Python 2.x 和 3.x:

中应该相同
alvas@ubi:~$ python2
Python 2.7.11 (default, Dec 15 2015, 16:46:19) 
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> type(u'man')
<type 'unicode'>
>>> type('man')
<type 'str'>
>>> u'man' == 'man'
True

alvas@ubi:~$ python3
Python 3.4.1 (default, Jun  4 2014, 11:27:44) 
[GCC 4.8.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> type(u'man')
<class 'str'>
>>> type('man')
<class 'str'>
>>> u'man' == 'man'
True

并且在 Python 2 中,当您 必须 或需要从 unicode 转换为 str 类型时,让我们说一下类型检查或其他内容,例如:

alvas@ubi:~$ python3
>>> u'man' == 'man'
True
>>> type(u'man') == type('man')
True
>>> exit()
alvas@ubi:~$ python2
>>> u'man' == 'man'
True
>>> type(u'man') == type('man')
False

那么您应该可以简单地将其转换为 str(u'man')u'man'.encode('utf-8')

但是如果您的 unicode 字符串超出了 ascii 范围并且您试图将其写入文件或将其打印到可能没有将 defaultencoding 设置为的控制台,则可能会出现一些 "pain" / 无穷无尽的错误'utf-8'。在那种情况下,观看 https://www.youtube.com/watch?v=sgHbC6udIqc


此外,这里还有与 u'...' 前缀相关的类似问题:

  • What does the 'u' symbol mean in front of string values?
  • Why is there a 'u' before every line of my output?
  • Python string prints as [u'String']
  • What's the u prefix in a python string
  • Printing a string prints 'u' before the string in Python?