【问题标题】:How to strip the leading Unciode characters from a file?如何从文件中去除前导 Unicode 字符?
【发布时间】:2015-07-31 09:23:21
【问题描述】:

我正在处理几千个 xml 文件并且有一些问题文件。

在每种情况下,它们都包含前导 Unicode 字符,例如 C3 AF C2 BB C2 BFEF BB BF 等。

在所有情况下,文件只包含 ASCII 字符(在标题字节之后),因此将它们转换为 ASCII 不会有数据丢失的风险。

我不能更改磁盘上文件的内容,只能将它们用作脚本的输入。

在最简单的情况下,我很乐意将此类文件转换为 ASCII(所有输入文件都经过解析、一些更改并写入输出目录,第二个脚本将在其中处理它们。)

我将如何编码?当我尝试时:

with open(filePath, "rb") as file:
    contentOfFile = file.read()

unicodeData = contentOfFile.decode("utf-8")
asciiData = unicodeData.encode("ascii", "ignore")

with open(filePath, 'wt')  as file:
    file.write(asciiData)

我收到错误must be str, not bytes

我也试过了

    asciiData = unicodedata.normalize('NFKD', unicodeData).encode('ASCII', 'ignore')

结果相同。我该如何纠正?

或者有没有其他方法可以隐藏文件?

【问题讨论】:

  • 从技术上讲,这些不是字符;它们是 BOM 字节。理想情况下,当以 Unicode 文本读取文件时,它们不会出现在输入流中(但我不知道 Python 如何处理 BOM)。

标签: python python-3.x unicode


【解决方案1】:
...
asciiData = unicodeData.encode("ascii", "ignore")

asciiData 是字节对象,因为它已编码。打开文件时需要使用二进制模式而不是文本模式:

with open(filePath, 'wb')  as file:  # <---
    file.write(asciiData)

【讨论】:

  • 糟糕,我突然遇到了一个异常:'utf-8' codec can't decode byte 0xfc in position 1410: invalid start byte :-(
  • ['Traceback (last most recent call last): ', ' File "/usr/lib/python3.2/xml/etree/ElementTree.py", line 1668, in feed self._parser. Parse(data, 0) ', 'xml.parsers.expat.ExpatError: junk after document element: line 56, column 0 ', '在处理上述异常期间,发生了另一个异常:', 'Traceback (最近一次调用最后一次): ', ' 文件 "/home/mawg/PycharmProjects/msgGen/msgGen.py",第 820 行,在 ParseInputFile
  • tree = ET.parse(inputFileName, parser=parser) ', ' 文件 "/usr/lib/python3.2/xml/etree/ElementTree.py",第 1223 行,在解析树中。 parse(source, parser) ', ' File "/usr/lib/python3.2/xml/etree/ElementTree.py", line 678, in parse parser.feed(data) ', ' File "/usr/lib/ python3.2/xml/etree/ElementTree.py",第 1670 行,在提要中 self._raiseerror(v) ','文件 "/usr/lib/python3.2/xml/etree/ElementTree.py",第 1543 行,在 _raiseerror raise err ', ' File "", line None\n', 'xml.etree.ElementTree.ParseError: junk after document element: line 56, column 0\n']
  • @Mawg,它看起来像一个不同的问题。发表一个单独的问题怎么样?
猜你喜欢
  • 2010-12-28
  • 2019-05-06
  • 1970-01-01
  • 2019-05-30
  • 2018-02-19
  • 2018-09-03
  • 1970-01-01
  • 2016-02-20
  • 2014-08-28
相关资源
最近更新 更多