3

我正在编写一个程序来“手动”将 csv 文件排列为正确的 JSON 语法,使用一个简短的 Python 脚本。从我用来readlines()将文件格式化为行列表的输入文件中,我对其进行操作并将其合并为单个字符串,然后将其输出到单独的 .txt 文件中。但是,输出包含乱码,而不是输入文件中存在的希伯来语字符,并且输出是水平双倍行距的(在每个字符之间添加一个空白字符)。据我所知,问题与编码有关,但我无法弄清楚是什么。当我检测到输入和输出文件的编码(使用.encoding属性)时,它们都返回None,这意味着它们使用系统默认值。技术细节:Python 2.7、Windows 7。

虽然关于这个主题有很多问题,但我没有找到我的问题的直接答案。在这种情况下,检测系统默认值对我没有帮助,因为我需要程序是可移植的。

这是代码:

def txt_to_JSON(csv_list):
    ...some manipulation of the list...
    return JSON_string
file_name = "input_file.txt"
my_file = open(file_name)
# make each line of input file a value in a list
lines = my_file.readlines()
# break up each line into a list such that each 'column' is a value in that list 
for i in range(0,len(lines)):
    lines[i] = lines[i].split("\t")
J_string = txt_to_JSON(lines)
json_file = open("output_file.txt", "w+")
json_file.write(jstring)
json_file.close()
4

2 回答 2

1

所有数据都需要编码才能存储在磁盘上。如果你不知道编码,你能做的最好的就是猜测。有一个图书馆:https ://pypi.python.org/pypi/chardet

我强烈推荐 Ned Batchelder 的演讲 http://nedbatchelder.com/text/unipain.html 了解详情。

有一个关于在 Windows 上使用“unicode”作为编码的解释:Unicode 和 UTF-8 有什么区别?

TLDR:Microsoft 使用 UTF16 作为 unicode 字符串的编码,但决定将其称为“unicode”,因为他们也在内部使用它。

即使 Python2 在字符串/unicode 转换方面有点宽松,您也应该习惯于始终在输入上解码并在输出上编码。

在你的情况下

filename = 'where your data lives'
with open(filename, 'rb') as f:
   encoded_data = f.read()
decoded_data = encoded_data.decode("UTF16")

# do stuff, resulting in result (all on unicode strings)
result = text_to_json(decoded_data)

encoded_result = result.encode("UTF-16")  #really, just using UTF8 for everything makes things a lot easier
outfile = 'where your data goes'
with open(outfile, 'wb') as f:
    f.write(encoded_result)
于 2013-04-24T18:34:55.040 回答
0

您需要告诉 Python 使用 Unicode 字符编码来解码希伯来字符。以下是如何在 Python 中读取 Unicode 字符的链接:Character reading from file in Python

于 2013-04-24T15:18:07.553 回答