【python – unicodedata.normalize(form,unistr)如何工作?】教程文章相关的互联网学习教程文章

将Unicode对象与非ASCII符号转换为字符串对象(在Python中)【代码】

我想通过在线服务发送中文字符,并返回生成的英文字符串.我正在使用简单的JSON和urllib. 是的,我在宣布.# -*- coding: utf-8 -*-在我的代码之上. 现在一切正常,如果我给urllib一个字符串类型的对象,即使该对象包含什么是Unicode信息.我的功能叫做翻译. 例如:stringtest1 = '無與倫比的美麗'print translate(stringtest1)导致正确的翻译和做type(stringtest1) 确认这是一个字符串对象. 但如果这样做stringtest1 = u'無與倫比的美麗'...

Python:强制pprint将unicode字符串显示为字符串?【代码】

我正在使用unicode字符串(读取json输入的工件)打印一些数据结构,并且希望将结果看作字符串(即’foo’)而不是unicode字符串(即u’foo’). 如何在Python pprint模块中完成?>>> pprint.pprint(u'hello') # would prefer to see just 'hello' u'hello'解决方法:您可以创建自己的PrettyPrinter对象并覆盖格式方法.import pprintdef no_unicode(object, context, maxlevels, level):""" change unicode u'foo' to string 'foo' when ...

在Python中检查unicode字符串是否为NFC的有效方法?【代码】

我想检查字符串是否已经是NFC格式.目前我这样做:unicodedata.normalize('NFC', s) == s我这样做是为了大量的字符串,所以我想要高效.上述方法似乎很浪费.它转换为NFC,然后进行字符串比较. 有更有效的方法吗?我考虑过:len(unicodedata.normalize('NFC', s)) == len(s)这避免了字符串比较.但我不确定这是否总是正确的.如果NFC标准化始终改变非NFC字符串的长度,则此方法有效.这是一个有效的假设吗? 还有其他想法吗?解决方法:规范化...

python – 什么导致’unicode’对象在pyspark中没有属性’toordinal’?【代码】

我得到了这个错误,但我没有导致它.我的python代码在pyspark中运行.堆栈跟踪很长,我只展示其中的一些.所有的堆栈跟踪都没有显示我的代码,所以我不知道在哪里寻找.导致此错误的原因是什么?/usr/hdp/2.4.2.0-258/spark/python/lib/py4j-0.9-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)306 raise Py4JJavaError(307 "An error occurred while calli...

python – BeautifulSoup不给我Unicode【代码】

我正在使用美丽的汤来刮取数据. BS文档声明BS应该总是返回Unicode,但我似乎无法获得Unicode.这是一段代码片段import urllib2 from libs.BeautifulSoup import BeautifulSoup# Fetch and parse the data url = 'http://wiki.gnhlug.org/twiki2/bin/view/Www/PastEvents2007?skin=print.pattern'data = urllib2.urlopen(url).read() print 'Encoding of fetched HTML : %s', type(data)soup = BeautifulSoup(data) print 'Encoding o...

在不杀死Unicode的情况下,在Python 2中编码转义字符的正确方法是什么?【代码】

我想我会疯狂使用Python的unicode字符串.我正在尝试编码Unicode字符串中的转义字符而不转义实际的Unicode字符.我明白了:In [14]: a = u"Example\n"In [15]: b = u"Пример\n"In [16]: print a ExampleIn [17]: print b ПримерIn [18]: print a.encode('unicode_escape') Example\nIn [19]: print b.encode('unicode_escape') \u041f\u0440\u0438\u043c\u0435\u0440\n虽然我迫切需要(英语示例按照我的意愿工作,显然):I...

python – 我什么时候应该使用Unicode字符串?【代码】

我想在Python 2.7和我的django应用程序中应该何时使用Unicode字符串. 为每个字符串使用常规字符串是否是好习惯? 例如:// models.py # -*- coding: UTF-8 -*- class ModelClass(models.Model)field_name = models.ForeignKey(SomeModel, related_name=u'some_models')# ...class Meta:ordering = (u'created', u'name',)和// urls.py # -*- coding: UTF-8 -*- urlpatterns = patterns(u'',url(r'^a/$', views.some_view(), name=u...

在python中将字符串转换为unicode类型【代码】

我正在尝试这段代码:s = "????" '{:b}'.format(int(s.encode('utf-8').encode('hex'), 16))但是会发生以下错误:06001 UnicodeDecodeError: ‘ascii’ codec can’t decode byte 0xd3 in position 0: ordinal not in range(128)我试过{:b}’.format(int(s.encode(‘utf-8’).encode(‘hex’),16))但没有改变. 我该怎么办?解决方法:由于您使用的是python 2,因此s =“????”是一个字节字符串(无论您的终端使用什么编码,大概是utf8...

python – 不能在django模板中使用unicode字符串【代码】

我在django模板中使用了“B?MNTON”字符串,它引发了错误“’utf8’编解码器无法解码位置569中的字节0xd4:无效的连续字节”.但是当我使用“BO MON TOAN”字符串时,它不会引起错误.所以,我在模板中使用越南语,这是我的代码:{% extends "site_base.html" %} {% load i18n %} {% load staticfiles %} {% load url from future %}{% block body_base %}<div class="subject-box-title">B? M?N TOáN</div> {% endblock %}这是我的项目中...

如何解码消息的mime部分并在Python 2.7中获取** unicode **字符串?【代码】

这是一个尝试获取电子邮件消息的html部分的方法:from __future__ import absolute_import, division, unicode_literals, print_functionimport emailhtml_mail_quoted_printable=b'''Subject: =?ISO-8859-1?Q?WG=3A_Wasenstra=DFe_84_in_32052_Hold_Stau?= MIME-Version: 1.0 Content-type: multipart/mixed;Boundary="0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBBF4C4DFD01253"--0__=4EBBF4C4DFD012538f9e8a93df938690918c4EBB...

Python 2.6.5支持Unicode吗?为什么listdir()没有,但Python 3.1.2确实显示了Unicode?【代码】

据说Python 2.6.5支持Unicode?为什么listdir()不在IDLE中,但Python 3.1.2确实在IDLE中显示Unicode? (这是在Windows 7上测试的) 以下代码是相同的行为:for dirname, dirnames, filenames in os.walk('c:\path\somewhere'):for subdirname in dirnames:print (os.path.join(dirname, subdirname))for filename in filenames:print (os.path.join(dirname, filename))更新:unicode在文件名中,而不在路径中…解决方法:Unicode字符串...

Python保存正确处理str / unicode的序列化?【代码】

除了PyYAML之外,是否有正确处理unicode / str的安全Python数据序列化库? 例如:>>> json.loads(json.dumps([u"x", "x"])) [u'x', u'x'] # Both unicode >>> msgpack.loads(msgpack.dumps([u"x", "x"])) ['x', 'x'] # Neither are unicode >>> bson.loads(bson.dumps({"x": [u"x", "x"]})) {u'x': [u'x', 'x']} # Dict keys become unicode >>> pyamf.decode(pyamf.encode([u"x", "x"])).next() [u'x', u'x'] # Both are unicode请...

python – numpy中的Unicode元素字符串比较【代码】

我有一个关于与numpy和字符串数组进行相等比较的问题.假设我定义了以下数组:x = np.array(['yes', 'no', 'maybe'])然后我可以测试与其他字符串的相等性,并且它与单个字符串进行元素明智的比较(以下,我认为,这里的广播规则:http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html?):'yes' == x #op : array([ True, False, False], dtype=bool)x == 'yes' #op : array([ True, False, False], dtype=bool)但是,...

python – UnicodeWarning:Tkinter中的特殊字符【代码】

我在Tkinter(Python 2.7)中编写了一个程序,这是挪威语中的一个scrabblehelper,包含一些特殊字符(),这意味着我的wordlist(ordliste)包含带有特殊字符的单词. 当我运行我的函数finnord(c *)时,它返回’cd’.我正在使用entry.get()来获取放入我的函数的单词. 我的问题是entry.get()的编码.我有本地编码UTF-8,但是当我在我的输入框中写入任何特殊字符并将它们与我的wordliste匹配时,我得到一个UniCodeError. 这是我的输出.Warning (fro...

修复由另一种语言引起的Python Unicode错误【代码】

我收到这个错误:UnicodeEncodeError: ‘ascii’ codec can’t encode characters in position 52-57: ordinal not in range(128)导致错误的代码:f.write(textwrap.dedent(unicode(the_string))我想写的字符串摘自一个网站,其中包含英语和日语(用于测试)外语单词和名称的音译,例如コンピュータ(konpyūta,“computer”)和ロンドン(Rondon,“London”). (一些已归化的外国借款可能不会以片假名呈现.) 在Python中处理字符串时使用另...