gpt4 book ai didi

python - 如何让我的 Python 解析以下文本?

转载 作者:行者123 更新时间:2023-12-01 05:42:01 24 4
gpt4 key购买 nike

我有一个文本示例:

"PROTECTING-ħarsien",

我正在尝试使用以下内容进行解析

import csv, json

with open('./dict.txt') as maltese:
entries = maltese.readlines()
for entry in entries:
tokens = entry.replace('"', '').replace(",", "").replace("\r\n", "").split("-")
if len(tokens) == 1:
pass
else:
print tokens[0] + "," + unicode(tokens[1])

但是我收到一条错误消息

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in position 0: ordinal not in range(128)

我做错了什么?

最佳答案

看来 dict.txt 是 UTF-8 编码的(ħ 在 UTF-8 中是 0xc4 0xa7)。

你应该open the file as UTF-8 ,那么:

import codecs
with codecs.open('./dict.txt', encoding="utf-8") as maltese:
# etc.

然后您将可以使用 Unicode 字符串而不是字节串;因此,您不需要对它们调用 unicode(),但您可能必须将它们重新编码为要输出到的终端的编码。

关于python - 如何让我的 Python 解析以下文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17292393/

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