【问题标题】:Trying to run a defined function with a delay尝试延迟运行定义的函数
【发布时间】:2014-02-07 21:13:12
【问题描述】:

我正在尝试将 csv 文件第一列中的值增量加载到 URL 中,并以 5 秒的延迟一次请求一个 URL。第一列中的每个值都应替换“theid”

这是我目前的代码:

 # I have a defined function
 def withid (theid):
    """"""


    global cache

    dupe = False

    theurl = "{0}{1}{2}".format(OMDBURL, "?i=", theid)

    response = urllib2.urlopen(theurl)

    movdata = json.load(response)

    for mov in cache:
        if movdata[MKEY[1]] == mov[MKEY[1]]:
            dupe = True
    if not dupe:
        cache.append(movdata)



outfile2 = open('outputrows2-shortened.csv', 'rb')
for row in outfile2:
  theid = outfile2(row[0])
  time.sleep(5)

输出:TypeError:“文件”对象不可调用

【问题讨论】:

  • 还有……有什么问题?
  • 它不起作用,我只是收到上面的错误消息
  • 那是因为withid(现在)返回一个字典;您想将其附加到 jsonlist,而不是相反。请改用jsonlist.append(withid(row[0]))
  • 不幸的是,我收到了一个 HTTP 错误,意思是,我认为该 url 没有填充来自该列的数据

标签: python html json parsing csv


【解决方案1】:

您的withid() 函数永远不会返回任何内容。尝试在末尾添加return movdata

这是一个重写的版本,可能会有所帮助:

import csv
import json
import time
import urllib2

PAGE_DELAY = 5.    # time between loading pages
PAGE_LOAD  = 0.3   # how long it takes to load a page

make_url = 'http://www.imdb.com/title/tt{}/'.format

def get_csv_column(csv_fname, col, **kwargs):
    with open(csv_fname, 'rb') as inf:
        incsv = csv.reader(inf, **kwargs)
        column = [row[col] for row in incsv]
    return column

def get_data_by_id(id):
    url = make_url(id)
    response = urllib2.urlopen(url)
    data = json.load(response)
    return id,data

def delayed(delay, fn, *args):
    time.sleep(delay)
    return fn(*args)

def human_time(seconds):
    if seconds >= 86400:
        return '{:0.1f} days'.format(seconds / 86400.)
    elif seconds >= 3600:
        return '{:0.1f} hours'.format(seconds / 3600.)
    elif seconds >= 60:
        return '{:0.1f} minutes'.format(minutes / 60.)
    else:
        return '{:0.1f} seconds'.format(seconds)

def main():
    ids = get_csv_column('outputrows2.csv', 0)

    expected = (PAGE_DELAY + PAGE_LOAD) * len(ids)
    print('This will take about {}.'.format(human_time(expected)))

    results = (delayed(PAGE_DELAY, get_data_by_id, id) for id in ids)
    moviedata = dict(results)     # => gives dict of {id:data}

if __name__=="__main__":
    main()

【讨论】:

  • 我可以将这些定义中的哪一个输出到文本文件中?
  • @kegewe: 你想把什么放到文本文件中? data 是作为 json 返回的任何内容的字典;您需要从中提取您想要的任何内容并将其发送到您的输出文件。
  • 我想要文本文件每一行中每个 ID 的整个 JSON 字符串
  • @kegewe: 然后不要使用json.load(file),使用file.read() 并直接作为字符串返回。
  • 问题是我想稍后使用 json 格式的数据,因为print moviedata 似乎工作,我想知道我是否可以使用我刚刚进行的上述编辑
猜你喜欢
  • 2018-09-17
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
  • 2020-04-20
  • 2015-06-23
  • 2013-06-19
  • 1970-01-01
  • 2011-11-04
相关资源
最近更新 更多