Python 将撇号写入文件

标签 python python-3.x string-formatting

我正在使用 Python 将下载的 Facebook Messenger 对话从 JSON 转换为文本文件。我已将 JSON 转换为文本,一切看起来都很好。我需要删除不必要的信息并反转消息的顺序,然后将输出保存到文件中,我已经完成了。但是,当我使用 Python 格式化消息时,当我查看输出文件时,有时不是撇号,而是 â。

我的 Python 不太好,因为我通常使用 Java,所以可能还有很多地方我可以改进。如果有人能为这个问题建议一些更好的标签,我也会非常感激。

撇号工作示例:您不会制作它们,是吗?

撇号不起作用的示例:这只是我发现的一个按钮

是什么导致这种情况发生,为什么每次有撇号时不会发生?

这是脚本:

#/usr/bin/python3

import datetime

def main():

    input_file = open('messages.txt', 'r')
    output_file = open('results.txt', 'w')

    content_list = []
    sender_name_list = []
    time_list = []

    line = input_file.readline()

    while line:
        line = input_file.readline()

        if "sender_name" in line:
            values = line.split("sender_name")
            sender_name_list.append(values[1][1:])

        if "timestamp_ms" in line:
            values = line.split("timestamp_ms")
            time_value = values[1]
            timestamp = int(time_value[1:])         
            time = datetime.datetime.fromtimestamp(timestamp / 1000.0)      
            time_truncated = time.replace(microsecond=0)
            time_list.append(time_truncated)    

        if "content" in line:
            values = line.split("content")
            content_list.append(values[1][1:])

    content_list.reverse()
    sender_name_list.reverse()
    time_list.reverse()

    for x in range(1, len(content_list)):
        output_file.write(sender_name_list[x])
        output_file.write(str(time_list[x]))
        output_file.write("\n")
        output_file.write(content_list[x])
        output_file.write("\n\n")


input_file.close()
output_file.close()

if __name__ == "__main__":
    main()

编辑: 问题的答案是添加

import codecs
input_file = codecs.open('messages.txt', 'r', 'utf-8')
output_file = codecs.open('results.txt','w', 'utf-8')

最佳答案

在没有看到传入数据的情况下很难确定,但我怀疑您得到的不是撇号(Unicode U+0027 ' APOSSTROPHE),而是一个等效的花括号( U+2019 '右单引号) 试图被解释为老式的 ascii。

而不是

output_file = open('results.txt', 'w')

尝试

import codecs
output_file = codecs.open('results.txt','w', 'utf-8')

您可能还需要输入文件中的等效内容。

关于Python 将撇号写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54937768/

相关文章:

python - 如何修复("ValueError: You are trying to load a weight file containing 16 layers into a model with 0 layers")

C 中 sizeof() 返回值的正确格式说明符

Java 字符串时间格式

python - 根据邮政编码在真实 map 上显示数据

python - 自动化构建 LinkedList 的过程

python - 如何在 Tensorflow 中获得向量的逆累积和

python - 使用unittest和Python 3.6导入时出错

python - 每次我在终端中运行python命令时,系统崩溃,如何摆脱/opt/miniconda3/bin/python?

python - 类型错误 : '>' not supported between instances of 'int' and 'str'

java - 在Java的System.out中以表格格式输出