似乎有两种不同的方法将字符串转换为字节,如TypeError的答案所示:'str'不支持缓冲区接口
哪种方法更好或更好Pythonic?或者只是个人喜好?
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
Run Code Online (Sandbox Code Playgroud) 从Python 2.6 shell:
>>> import sys
>>> print sys.getdefaultencoding()
ascii
>>> print u'\xe9'
é
>>>
Run Code Online (Sandbox Code Playgroud)
我希望在print语句之后有一些乱码或错误,因为"é"字符不是ASCII的一部分,我没有指定编码.我想我不明白ASCII是默认编码的意思.
编辑
在Python 2.7中,如何将latin1字符串转换为UTF-8.
例如,我正在尝试将é转换为utf-8.
>>> "é"
'\xe9'
>>> u"é"
u'\xe9'
>>> u"é".encode('utf-8')
'\xc3\xa9'
>>> print u"é".encode('utf-8')
é
Run Code Online (Sandbox Code Playgroud)
字母是é,它是LATIN SMALL LETTER E WITH ACUTE(U + 00E9)UTF-8字节编码为:c3a9
拉丁字节编码为:e9
如何获得拉丁字符串的UTF-8编码版本?有人可以举例说明如何转换é?
我的代码如下所示:
for file in glob.iglob(os.path.join(dir, '*.txt')):
print(file)
with codecs.open(file,encoding='latin-1') as f:
infile = f.read()
with codecs.open('test.txt',mode='w',encoding='utf-8') as f:
f.write(infile)
Run Code Online (Sandbox Code Playgroud)
我使用的文件用Latin-1编码(我无法用UTF-8打开它们).但我想在utf-8中编写生成的文件.
但是这个:
<Trans audio_filename="VALE_M11_070.MP3" xml:lang="español">
<Datos clave_texto=" VALE_M11_070" tipo_texto="entrevista_semidirigida">
<Corpus corpus="PRESEEA" subcorpus="ESESUMA" ciudad="Valencia" pais="España"/>
Run Code Online (Sandbox Code Playgroud)
取而代之的是(在gedit中):
<Trans audio_filename="VALE_M11_070.MP3" xml:lang="espa???????????`????????????????????????????
Run Code Online (Sandbox Code Playgroud)
如果我在终端上打印它,它显示正常.
当我使用LibreOffice Writer打开生成的文件时,我得到的更令人困惑的是:
<#T#r#a#n#s# (and so on)
Run Code Online (Sandbox Code Playgroud)
那么如何正确地将latin-1字符串转换为utf-8字符串?在python2中,它很容易,但在python3中,它似乎让我很困惑.
我尝试过这些不同的组合:
#infile = bytes(infile,'utf-8').decode('utf-8')
#infile = infile.encode('utf-8').decode('utf-8')
#infile = bytes(infile,'utf-8').decode('utf-8')
Run Code Online (Sandbox Code Playgroud)
但不知怎的,我总是以同样奇怪的输出结束.
提前致谢!
编辑:这个问题与评论中链接的问题不同,因为它涉及Python 3,而不是Python 2.7.
Unicode使用 python 写入 .pdf时,我遇到了变量内容问题。
它输出这个错误:
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013'
Run Code Online (Sandbox Code Playgroud)
基本上是什么被抓住了。
我曾尝试采用该变量,其中内容有一个“破折号”并用“ .encode('utf-8')”重新定义它,例如,如下所示:
Body = msg.Body
BodyC = Body.encode('utf-8')
Run Code Online (Sandbox Code Playgroud)
现在我收到以下错误:
Traceback (most recent call last):
File "script.py", line 37, in <module>
pdf.cell(200, 10, txt="Bod: " + BodyC, ln=4, align="C")
TypeError: can only concatenate str (not "bytes") to str
Run Code Online (Sandbox Code Playgroud)
下面是我的完整代码,我怎么能简单地修复 ' Body' 变量内容中的Unicode 错误。
转换为utf-8or western, ' latin-1'之外的任何内容。有什么建议?
完整代码:
from fpdf import FPDF
import win32com.client
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
msg = outlook.OpenSharedItem(r"C:\User\language\python\Msg-To-PDF\test_msg.msg") …Run Code Online (Sandbox Code Playgroud) python ×6
encoding ×4
utf-8 ×3
unicode ×2
ascii ×1
console ×1
fpdf ×1
latin1 ×1
pdf ×1
python-2.7 ×1
python-2.x ×1
python-3.5 ×1
python-3.7 ×1
python-3.x ×1
string ×1