我是蟒蛇的新手。为一个非常基本的问题道歉。
我正在使用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”。
提前谢谢..!
发布于 2016-01-25 06:27:54
尝试正确的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']
发布于 2016-01-25 12:11:27
简而言之::
没有必要将独角兽列表转换为字符串。他们是一样的
In long:
字符串对象中的u'...'
前缀表示Python2.0中引入的Unicode对象,请参阅https://docs.python.org/2/tutorial/introduction.html#unicode-strings
从Python2.0开始,程序员可以使用一种用于存储文本数据的新数据类型: Unicode对象。它可以用于存储和操作Unicode数据(请参阅http://www.unicode.org/),并与现有的字符串对象很好地集成,在必要时提供自动转换。
从Python3.0开始,请参阅https://docs.python.org/3.2/tutorial/introduction.html#about-unicode
从Python3.0开始,所有字符串都支持Unicode (参见http://www.unicode.org/)。
无论默认字符串类型是什么,在检查等效性时,它们在Python2.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
在Python2中,当必须或需要从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范围,并且试图将其写入控制台或将其打印到控制台,而控制台可能没有将默认编码设置为'utf-8‘,则可能会出现一些“痛苦”/无休止的错误。在这种情况下,请看https://www.youtube.com/watch?v=sgHbC6udIqc
此外,以下是与u'...'
前缀相关的类似问题:
https://stackoverflow.com/questions/34986329
复制相似问题