我有一个文本文件,每行都有像bytearray一样的格式化字符串,例如: B'{ “删除”:{ “地位”:{ “ID”:554377123205378048, “ID_STR”: “554377123205378048”, “USER_ID”:981513812, “user_id_str”: “981513812”}, “TIMESTAMP_MS”: “1508108338761”} }“
(这来自使用命令行放入文本文件的流式推特数据,例如“python twitterstream.py> output.txt”)
我现在正在尝试读取每一行并在其上使用json.loads()来获取该行应该是的字典。
如果我使用line = open('output.txt')。readline()我得到一个如下所示的字符串: 'B \'{ “删除”:{ “地位”:{ “ID”:554377123205378048, “ID_STR”: “554377123205378048”, “USER_ID”:981513812, “user_id_str”: “981513812”}, “TIMESTAMP_MS”:“1508108338761 “}} \ '\ n'
注意添加的额外转义序列,如'b \'。 json.loads()无法解析此行。如果我手动将内容复制到python控制台,我可以让它解析原始行,这样行本身就可以了。我的文件I / O怎么回事搞乱了?
此外,当我手动将行复制到变量时,它被保存为bytearray类型(字节),所以我想问题是如何让python在文件行中读取为文字字节数组,因为它们被写入?
答案 0 :(得分:0)
>>> ast.literal_eval("""b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'""")
b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'
>>> json.loads(ast.literal_eval("""b'{"delete":{"status":{"id":554377123205378048,"id_str":"554377123205378048","user_id":981513812,"user_id_str":"981513812"},"timestamp_ms":"1508108338761"}}'""").decode('utf-8'))
{'delete': {'status': {'user_id_str': '981513812', 'id_str': '554377123205378048', 'id': 554377123205378048, 'user_id': 981513812}, 'timestamp_ms': '1508108338761'}}