【问题标题】:Python: loop doing the same thing to one item n-times as opposed doing it once to n-itemsPython:循环对一个项目做同样的事情 n 次,而不是对 n 项目做一次
【发布时间】:2011-08-18 14:34:05
【问题描述】:

这是一个例子: 我正在尝试获取一系列 XML 页面,然后从中提取数据。

它下载每个单独的页面,就像 while 循环设计的那样,但是 tester() 函数从它下载的第一个文件中打印数据 V 次,尽管它在每次循环后下载并清除文件。

这简直要了我的命,我做错了什么?

def tester():
    with open('raw.txt') as myFile:
        test = linecache.getline('raw.txt', 12)
        print test
        test = ""
        myFile.close

def grab_data(Year, rcvote):
    link = "XXX/%s/roll%s.xml" % (Year, rc)
    site = urllib2.urlopen(link)
    localFile = open('raw.txt', 'w')
    localFile.write(site.read(100000))
    localFile.close()
    tester()


while (V !=0):
    rc = str(V)
    if (len(rc) == 2):
        rc = "0%s" % (rc)
    elif (len(rc) == 1):
        rc = "00%s" % (rc)
    else:
        rc = rc
    grab_data(Year, rc)
    V = V - 1

【问题讨论】:

  • 更多吹毛求疵:如果您直接使用它,为什么要将rc 作为rcvote 传递给grab_data
  • 与您的问题无关,请尝试使用此单行代码将V 转换为零填充字符串:rc = '%03d' % V

标签: python loops while-loop


【解决方案1】:

问题在于 linecache 模块。它假定同名文件是相同的。

但是为什么将数据写入文件只是为了再次读取它呢?

def tester(text):
    line12 = text.splitlines()[11]
    print line12

def grab_data(year, rcvote):
    link = "XXX/%s/roll%03d.xml" % (year, rcvote)
    site = urllib2.urlopen(link)
    tester(site.read(100000))

while v:
    grab_data(year, rc)
    v -= 1

【讨论】:

  • 我是 python 新手,所以我并不总是做出最好的决定。有什么更好的方法?
  • 没错。同样linecache.checkcache() 将重新检查缓存的文件,如果它们在磁盘上发生更改,则将它们从缓存中删除。但是在这个例子中仍然使用linecache 没有什么意义。为什么不直接从文件或 url 读取。
  • for V in xrange(start, 0, -1): 怎么样?
  • 每个人的 cmets 都非常有帮助。你们对阅读什么内容以学习更有效的编码有什么建议吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-20
  • 2013-04-18
  • 2013-07-12
  • 2020-05-23
  • 2014-11-06
  • 2015-12-14
  • 1970-01-01
相关资源
最近更新 更多