正在将带u'…'的字符串列表转换为普通字符串列表

2024-09-30 16:40:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

我得到的结果是:

^{pr2}$

但对于我的程序,我需要插入如下数组:

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

如何获得如上所述的输出并从输出中删除“u”。在

提前谢谢。。!在


Tags: 代码fromimport单词wordnetensynonymspattern
2条回答

简而言之:

不需要将您的unicode列表转换为字符串。他们是一样的


长:

string对象中的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.

从Python3.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

在Python2中,当必须或需要从unicode转换为{}类型时,让我们假设进行类型检查或其他操作,例如:

^{pr2}$

然后您应该能够简单地将其转换为str(u'man')或{}。在

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


此外,以下是与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']

相关问题 更多 >