【问题标题】:Is there a way to convert to unicode the text in a file? in Python [duplicate]有没有办法将文件中的文本转换为 unicode?在 Python [重复]
【发布时间】:2016-03-12 21:56:34
【问题描述】:

我正在从巴西页面编写抓取代码,并将结果写入文件,问题是我从代码中得到的结果在 ASCII 中不受支持,并给了我这个错误:

文件“testUnicode.py”,第 6 行 SyntaxError:第 6 行文件 testUnicode.py 中的非 ASCII 字符“\xc3”,但未声明编码;详情见http://www.python.org/peps/pep-0263.html

所以我在这里找到了解决该错误的答案:

file.write(news.encode('uft8'))

它起作用了,因为它使我摆脱了错误,但问题是我仍然以一种糟糕的方式获取信息,如下所示:

Em tom de desabafo, peemedebista diz que, no 1º mandato, foi um 'vice decorativo' Coalizão diz que usará sua maioria na Assembleia para libertar antichavistas Segundo autoridades, casal acusado das mortes estava 'radicalizado havia algum tempo' 进入 mulheres, ñndice vai a 52%; maioria da população aprova movimentos feministas Manifestantes bloqueiam ruas contra a reorganização das escolas; houve Discussionão com 驾驶者 Animalzinho é menor que um grão de gergelim

有没有办法解决这个问题?

【问题讨论】:

  • 你需要知道原文是用什么编码的。
  • 我不认为是utf-8。使用正确的编码

标签: python file unicode


【解决方案1】:

原来的错误:

File "testUnicode.py", line 6 
  SyntaxError: Non-ASCII character '\xc3' in file testUnicode.py on line 6, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details

是因为您的文件有UTF-8 字符,请声明编码:

# -*- coding: utf-8 -*-

导致第二个问题的原因是,将您的文本解释为latin1 编码而不是utf8,例如

c = u'\u00e3'  # Codepoint for LATIN SMALL LETTER A WITH TILDE

c.encode('utf8')  # UTF8 encoding produces 2 bytes
>>> '\xc3\xa3'

# Those bytes, read as latin1
print c.encode('utf8').decode('latin1')
>>> ã

# E.g. \xc3 => Ã
#      \xa3 => £ 

所以你的文件写为utf8,但读为latin1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-04-23
    • 2023-04-09
    • 1970-01-01
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多