Skip to main content
 首页 » 编程设计

python之在 Python 中循环 json 文件

2025年05月04日12artech

我有 10 个名为 Herald500_2005、Herald500_2006.... Herald500_2015 的 json 文件。我试图在每个文件中进行相同的关键字词搜索。我不想一个一个地做,而是希望能够循环进行。到目前为止,我已经尝试了以下代码:

for i in range(5,15): 
    df = pandas.DataFrame([json.loads(l) for l in open('Herald500_200i.json')]) 
# Parse dates and set index 
    df.date = pandas.to_datetime(df.date) 
    df.set_index('date', inplace=True) 
# match keywords 
    matchingbodies = df[df.body.str.contains("|".join(keywords3))&df.body.str.contains("|".join(keywords2))&df.body.str.contains("|".join(keywords1))].body 
# Count by month 
    counts = matchingbodies.groupby(lambda x: x.month).agg(len) 
 
    print "TH 200i"  
    print counts 

通过运行此代码,我收到以下错误:

<ipython-input-9-76f2d2649df0> in <module>() 
      1 for i in range(5,15): 
----> 2     df = pandas.DataFrame([json.loads(l) for l in open('Herald500_200i.json')]) 
      3 # Parse dates and set index 
      4     df.date = pandas.to_datetime(df.date) 
      5     df.set_index('date', inplace=True) 
 
IOError: [Errno 2] No such file or directory: 'Herald500_200i.json' 

知道如何更正代码吗?

亲切的问候

请您参考如下方法:

您应该使用字符串格式化 将i 值放入字符串中:

open('Herald500_200%d.json' % i)  

或者:

open('Herald500_200{0}.json'.format(i))  

或者,由于这些是年,为了简化前导零格式化问题的处理,直接循环这些年:

for year in range(2005, 2016):  # note the 2016 here - the upper bound is non-inclusive 
    df = pandas.DataFrame([json.loads(l) for l in open('Herald500_%d.json' % year)])