小编I.P*_*.P.的帖子

Python3:将Latin-1转换为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.

python encoding utf-8 python-3.5

9
推荐指数
1
解决办法
4947
查看次数

标签 统计

encoding ×1

python ×1

python-3.5 ×1

utf-8 ×1