gpt4 book ai didi

python - 如何让 python 在读写 Unicode 文本文件时更加友好?

转载 作者:太空宇宙 更新时间:2023-11-04 11:03:50 24 4
gpt4 key购买 nike

我发现即使是现代 Python 版本(如 3.x)也无法检测文本文件上的 BOM。我想知道是否有任何模块可以通过替换用于读取和写入文本的 open()codecs.open() 函数来将此缺失的功能添加到 Python文件。

最佳答案

建议的解决方案here对我来说仍然不错(这里是该代码的修改版本,仍然在 Python 2 中,而不是 Python 3 中,并且有一个用法示例):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import codecs, logging, sys
logging.basicConfig(level=logging.INFO)
bomdict = {
codecs.BOM_UTF8 : 'UTF8',
codecs.BOM_UTF16_BE : 'UTF-16BE',
codecs.BOM_UTF16_LE : 'UTF-16LE' }

def read_unicode(filename):
the_text = open(filename, 'r').read()
for bom, encoding in bomdict.items():
if the_text.startswith(bom):
logging.info('BOM found, using %s', encoding)
the_text = the_text[len(bom):]
break
else:
logging.info('No BOM, using utf8')
encoding = 'UTF8'
return the_text.decode(encoding)

f = open('x.txt', 'wb')
f.write(codecs.BOM_UTF16_LE)
f.write(u'zeé fóo!'.encode('UTF-16LE'))
f.close()

print read_unicode('x.txt')

关于python - 如何让 python 在读写 Unicode 文本文件时更加友好?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com