我有一个unicode字符串'%C3%A7%C3%B6asd+fjkls%25asd',我想解码这个字符串.
我用过,urllib.unquote_plus(str)但它的工作错了.
çöasd+fjkls%asdçöasd fjkls%asd双重编码的utf-8字符(%C3%A7和%C3%B6)被解码错误.
我的python版本在linux发行版下是2.7.获得预期结果的最佳方法是什么?
根据文档,在Python 2.7.3中,shlex应该支持UNICODE.但是,当运行下面的代码时,我得到:UnicodeEncodeError: 'ascii' codec can't encode characters in position 184-189: ordinal not in range(128)
难道我做错了什么?
import shlex
command_full = u'software.py -fileA="sequence.fasta" -fileB="??????.fasta.txt" -output_dir="..." -FORMtitle="tst"'
shlex.split(command_full)
Run Code Online (Sandbox Code Playgroud)
确切的错误如下:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 275, in split
lex = shlex(s, posix=posix)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/shlex.py", line 25, in __init__
instream = StringIO(instream)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 44-49: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
这是我的mac使用python从macports输出的.我在使用"native"python 2.7.3的Ubuntu机器上得到完全相同的错误.
我正在尝试加载/usr/share/matplotlib/sample_data/goog.npy:
datafile = matplotlib.cbook.get_sample_data('goog.npy', asfileobj=False)
np.load(datafile)
Run Code Online (Sandbox Code Playgroud)
它在Python 2.7中很好,但在Python 3.4中引发了异常:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd4 in position 1: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我认为它与bytes/str/unicodePython 2和3之间的不一致有关,但不知道如何通过.
题:
.npy从Python 3中的Python 2 加载文件(NumPy数据)?在Python 2.7中,当将一个unicode字符串传递给XML声明fromstring()中包含的ElementTree 方法时encoding="UTF-16",我得到一个ParseError,说明指定的编码不正确:
>>> from xml.etree import ElementTree
>>> data = u'<?xml version="1.0" encoding="utf-16"?><root/>'
>>> ElementTree.fromstring(data)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files (x86)\Python 2.7\lib\xml\etree\ElementTree.py", line 1300, in XML
parser.feed(text)
File "C:\Program Files (x86)\Python 2.7\lib\xml\etree\ElementTree.py", line 1642, in feed
self._raiseerror(v)
File "C:\Program Files (x86)\Python 2.7\lib\xml\etree\ElementTree.py", line 1506, in _raiseerror
raise err
xml.etree.ElementTree.ParseError: encoding specified in XML declaration is incorrect: line 1, column 30
Run Code Online (Sandbox Code Playgroud)
那是什么意思?是什么让ElementTree这么认为?
毕竟,我传递的是unicode代码点,而不是字节串.这里没有涉及编码.怎么会不正确?
当然,有人可能会争辩说任何编码都是不正确的,因为这些unicode代码点没有被编码.但是,为什么UTF-8不被拒绝为"错误编码"?
>>> ElementTree.fromstring(u'<?xml version="1.0" …Run Code Online (Sandbox Code Playgroud) 我试图在OSX上用python 3.5.1运行一个非常简单的例子,但我真的被困了.已经阅读了很多处理类似问题的文章,但我自己无法解决这个问题.您是否有任何提示如何解决此问题?
我想在mylist中定义正确编码的latin-1输出,没有任何错误.
我的代码:
# coding=<latin-1>
mylist = [u'Glück', u'Spaß', u'Ähre',]
print(mylist)
Run Code Online (Sandbox Code Playgroud)
错误:
Traceback (most recent call last):
File "/Users/abc/test.py", line 4, in <module>
print(mylist)
UnicodeEncodeError: 'ascii' codec can't encode character '\xfc' in position 4: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
我如何修复错误但仍然出现stdout(print)错误:
mylist = [u'Glück', u'Spaß', u'Ähre',]
for w in mylist:
print(w.encode("latin-1"))
Run Code Online (Sandbox Code Playgroud)
我得到的输出:
b'Gl\xfcck'
b'Spa\xdf'
b'\xc4hre'
Run Code Online (Sandbox Code Playgroud)
什么'locale'告诉我:
LANG="de_AT.UTF-8"
LC_COLLATE="de_AT.UTF-8"
LC_CTYPE="de_AT.UTF-8"
LC_MESSAGES="de_AT.UTF-8"
LC_MONETARY="de_AT.UTF-8"
LC_NUMERIC="de_AT.UTF-8"
LC_TIME="de_AT.UTF-8"
LC_ALL=
Run Code Online (Sandbox Code Playgroud)
什么 - >'python3'告诉我:
Python 3.5.1 (default, Jan 22 2016, 08:54:32)
[GCC 4.2.1 Compatible Apple LLVM 7.0.2 (clang-700.1.81)] …Run Code Online (Sandbox Code Playgroud) 请参阅我的系统上的以下输出:
[STEP 101] # python3 -c 'import sys; print(sys.stdout.encoding)'
ANSI_X3.4-1968
[STEP 102] #
[STEP 103] # locale
LANG=C
LANGUAGE=en_US:en
LC_CTYPE="C"
LC_NUMERIC="C"
LC_TIME="C"
LC_COLLATE="C"
LC_MONETARY="C"
LC_MESSAGES="C"
LC_PAPER="C"
LC_NAME="C"
LC_ADDRESS="C"
LC_TELEPHONE="C"
LC_MEASUREMENT="C"
LC_IDENTIFICATION="C"
LC_ALL=C
[STEP 104] #
Run Code Online (Sandbox Code Playgroud)
谷歌搜索但发现很少有关于它的信息.甚至Python的Python库参考(v3.5.2)也没有提到它.任何国际标准都定义了它?
(从接受的答案评论中复制权威参考:字符集)
当我使用时pipreqs,我遇到了这个问题。我使用 anaconda 和俄语 Windows。
root@DESKTOP-ETLLRI1 C:\Users\root\Desktop\resumes
$ pipreqs C:\Users\root\Desktop\resumes
Traceback (most recent call last):
File "C:\Users\root\Anaconda3\Scripts\pipreqs-script.py", line 9, in <module>
sys.exit(main())
File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 396, in main
init(args)
File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 341, in init
extra_ignore_dirs=extra_ignore_dirs)
File "C:\Users\root\Anaconda3\lib\site-packages\pipreqs\pipreqs.py", line 75, in get_all_imports
contents = f.read()
File "C:\Users\root\Anaconda3\lib\encodings\cp1251.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1206: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud) 我试图将包含非ascii字符的传入字节字符串转换为有效的utf-8字符串,以便我可以转储为json.
b = '\x80'
u8 = b.encode('utf-8')
j = json.dumps(u8)
Run Code Online (Sandbox Code Playgroud)
我希望j为'\ xc2\x80',但我得到:
UnicodeDecodeError: 'ascii' codec can't decode byte 0x80 in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)
在我的情况下,'b'来自mysql通过谷歌协议缓冲区,并填写了一些blob数据.
有任何想法吗?
编辑:我有一个以太网帧作为blob存储在mysql表中(请大家,请保持主题,不要讨论为什么表中有数据包).表格排序是utf-8,db层(sqlalchemy,non-orm)正在抓取数据并创建结构(谷歌协议缓冲区),它将blob存储为python"str".在某些情况下,我直接使用协议缓冲区,没有任何问题.在其他情况下,我需要通过json公开相同的数据.我注意到的是,当json.dumps()做了它的事情,'\ x80'可以用无效的unicode char替换(\ ufffd iirc)
这是一个小例子:
reg = ur"((?P<initial>[+\-])(?P<rest>.+?))$"
Run Code Online (Sandbox Code Playgroud)
(在这两种情况下文件都有-*- coding: utf-8 -*-)
在Python 2中:
re.match(reg, u"hello").groupdict()
# => {u'initial': u'\ud83d', u'rest': u'\udc4dhello'}
# unicode why must you do this
Run Code Online (Sandbox Code Playgroud)
然而,在Python 3中:
re.match(reg, "hello").groupdict()
# => {'initial': '', 'rest': 'hello'}
Run Code Online (Sandbox Code Playgroud)
上述行为是100%完美,但切换到Python 3目前不是一个选项.将3的结果复制到2中的最佳方法是什么,这适用于窄版和宽版Python?似乎是以"\ ud83d\udc4d"格式来找我,这就是让这个变得棘手的原因.
我已经使用从web服务检索的unicode字符串requests模块,它包含一个二进制文件的字节(PCL,因为它发生).其中一个字节的值为248,尝试对其进行base64编码会导致以下错误:
In [68]: base64.b64encode(response_dict['content']+'\n')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-68-8c1f1913eb52> in <module>()
----> 1 base64.b64encode(response_dict['content']+'\n')
C:\Python27\Lib\base64.pyc in b64encode(s, altchars)
51 """
52 # Strip off the trailing newline
---> 53 encoded = binascii.b2a_base64(s)[:-1]
54 if altchars is not None:
55 return _translate(encoded, {'+': altchars[0], '/': altchars[1]})
UnicodeEncodeError: 'ascii' codec can't encode character u'\xf8' in position 272: ordinal not in range(128)
In [69]: response_dict['content'].encode('base64')
---------------------------------------------------------------------------
UnicodeEncodeError Traceback (most recent call last)
C:\...\<ipython-input-69-7fd349f35f04> in <module>() …Run Code Online (Sandbox Code Playgroud) python base64 character-encoding unicode-string python-unicode
python-unicode ×10
python ×7
python-3.x ×3
unicode ×3
python-2.7 ×2
anaconda ×1
base64 ×1
elementtree ×1
encoding ×1
iso-8859-1 ×1
json ×1
numpy ×1
regex ×1
shlex ×1
url-encoding ×1
utf-8 ×1