用于Python中的循环json文件

用于Python中的循环json文件,python,Python,我有10个json文件名为Herald500_2005,Herald500_2006先驱500_2015。我试图在每个文件中进行相同的关键字搜索。我不想一个接一个地去做,而是希望能够在一个循环中去做。到目前为止,我已经尝试了以下代码: for i in range(5,15): df = pandas.DataFrame([json.loads(l) for l in open('Herald500_200i.json')]) # Parse dates and set index

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

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'
() 1表示范围(5,15)内的i: ---->2 df=pandas.DataFrame([json.loads(l)在open中表示l('Herald500_200i.json')) 3#解析日期并设置索引 4 df.date=截止日期时间(df.date) 5 df.设置索引(“日期”,就地=真) IOError:[Errno 2]没有这样的文件或目录:“Herald500_200i.json” 知道如何更正代码吗

您应该使用字符串格式将
i
值输入字符串:

open('Herald500_200%d.json' % 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)])
应使用字符串格式将
i
值输入字符串:

open('Herald500_200%d.json' % 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)])

工作非常出色,但唯一的问题是,到2010年时,它会尝试获得20010,我想我可以用范围(05,15)内的for I和open('Herald500_20%d.json'%I')来修复它,在@alecxe下效果非常好!工作非常出色,但唯一的问题是,到2010年时,它会尝试获得20010,我想我可以用范围(05,15)内的for I和open('Herald500_20%d.json'%I')来修复它,在@alecxe下效果非常好!你有11个文件,不是10个。你有11个文件,不是10个。