如何只在文本文件中保留 Big5 字符
How to only keep Big5 characters in a text file
我抓取了一些在台湾网站上找到的文字。我摆脱了 HTML 并且只保留了我需要的 txt 文件。 txt 文件的内容在 Firefox/Chrome 中正确显示。使用 Python3,如果我这样做 f = open(text_file).read()
,我会收到此错误:
'utf-8' codec can't decode byte 0xa1 in position 29: invalid start byte
ETA:我使用 ubuntu,所以我很高兴 Python 或终端中的任何解决方案!
如果我先 f = codecs.open(os.path.join(path, 'my_text.txt'), 'r', encoding='Big5')
然后 read()
我会收到这条消息:
'big5' codec can't decode byte 0xf9 in position 1724: illegal multibyte sequence
我只需要汉字,怎么只保留那些编码为Big5的?这会消除错误,是吗?
builtin open()
function 有 errors
参数:
with open(filename, encoding='utf-8', errors='replace') as file:
text = file.read()
您的文件可能使用了其他一些字符编码,或者甚至(如果保存文本的代码有问题)几种字符编码的混合。
您可以查看浏览器使用的编码,例如 Chrome:"More tools -> Encoding"。
我抓取了一些在台湾网站上找到的文字。我摆脱了 HTML 并且只保留了我需要的 txt 文件。 txt 文件的内容在 Firefox/Chrome 中正确显示。使用 Python3,如果我这样做 f = open(text_file).read()
,我会收到此错误:
'utf-8' codec can't decode byte 0xa1 in position 29: invalid start byte
ETA:我使用 ubuntu,所以我很高兴 Python 或终端中的任何解决方案!
如果我先 f = codecs.open(os.path.join(path, 'my_text.txt'), 'r', encoding='Big5')
然后 read()
我会收到这条消息:
'big5' codec can't decode byte 0xf9 in position 1724: illegal multibyte sequence
我只需要汉字,怎么只保留那些编码为Big5的?这会消除错误,是吗?
builtin open()
function 有 errors
参数:
with open(filename, encoding='utf-8', errors='replace') as file:
text = file.read()
您的文件可能使用了其他一些字符编码,或者甚至(如果保存文本的代码有问题)几种字符编码的混合。
您可以查看浏览器使用的编码,例如 Chrome:"More tools -> Encoding"。