我试图做一个json读取器,然后它将绘制一个条形图。但是我不明白问题出在哪里。
import json
from argparse import ArgumentParser
import dateutil.parser
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from datetime import datetime
def get_parser():
parser = ArgumentParser()
parser.add_argument('--file', '-f', required=True, help='The .jsonl file with all the posts')
return parser
if __name__ == '__main__':
parser = get_parser()
args = parser.parse_args()
with open(args.file) as f:
posts = []
for line in f:
post = json.loads(line)
created_time = dateutil.parser.parse(post['created_time'])
posts.append(created_time.strftime('%H:%M:%S'))
ones = np.ones(len(posts))
idx = pd.DatetimeIndex(posts)
my_series = pd.Series(ones, index=idx)
per_hour = my_series.resample('1H').sum().fillna(0)
fig, ax =plt.sublots()
ax.grid(True)
ax.set_title("Post Frequencies")
width = 0.8
ind = np.arange(len(per_hour))
plt.bar(ind, per_hour)
tick_pos = ind + width / 2
labels = []
for i in range(24):
d = datetime.now().replace(hour=i, minute=0)
labels.append(d.strftime('%H:%M'))
plt.xticks(tick_pos, labels, rotation=90)
plt.savefig('posts_per_hours.png')
我知道了
Traceback (most recent call last):
File "deneme1.py", line 20, in <module>
post = json.loads(line)
File "C:\Users\Nulla\AppData\Local\Programs\Python\Python37\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Nulla\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Nulla\AppData\Local\Programs\Python\Python37\lib\json\decoder.py", line 353, in raw_decode
obj, end = self.scan_once(s, idx)
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 2 column 1 (char 2)
每次我尝试在CMD中运行时都会出现此错误。
当我尝试运行时,我在PyCharm上也遇到了另一个错误
usage: deneme1.py [-h] --file FILE
deneme1.py: error: the following arguments are required: --file/-f
答案 0 :(得分:1)
您仅将文件的一行传递到json.loads()
。在这种情况下,我认为解析器会将行[
中的"status_updates": [
解释为status_updates的值,并期望将其用双引号引起来。您必须将整个文件作为字符串放入参数中,或者直接使用json.load()
从文件中解码。
收到PyCharm错误的原因是因为您没有提供文件作为参数。为此,您可以通过在运行配置的“参数”字段中添加--file YOURFILE
来解决此问题。
答案 1 :(得分:0)
像这样,8991行
{
"status_updates": [
{
"timestamp": 1530227779,
"attachments": [
{
"data": [
{
"external_context": {
"url": "https://www.youtube.com/attribution_link?a=SPSgj9f3J60&u=%2Fwatch%3Fv%3DFBnAZnfNB6U%26feature%3Dshare"
}
}
]
}
],
"data": [
{
"update_timestamp": 1530227779
}
],
"title": "G\u00c3\u00b6rkem Konuk bir ba\u00c4\u009flant\u00c4\u00b1 payla\u00c5\u009ft\u00c4\u00b1."
},
{
"timestamp": 1509278187,
"attachments": [
{
"data": [
{
"media": {
"uri": "photos_and_videos/ZamanTuneliFotograflari_mo2sWu_38g/22815474_10214623978142384_2654258887927801559_n_10214623978142384.jpg",
"creation_timestamp": 1509278175,
"media_metadata": {
"photo_metadata": {
"upload_ip": "176.218.70.223"
}
}
}
}
]
}
]
},