将项目从列表写入多个文件 - Python

时间:2012-09-19 17:53:47

标签: python list

我正在尝试将列表中的项目写入多个文件。我想根据日期命名每个文件。请记住,我知道我不应该使用正则表达式来抓取HTML,但暂时它很适合我。请原谅无知,但我是初学者。这种刮擦仅用于学术目的。先感谢您。

    from urllib import urlopen
    import re

    webpage = urlopen('x').read()
    date = re.compile('[0-9]{2}-[a-zA-Z]{3}-[0-9]{4}')
    article =  re.compile('<span>.*<div>', re.DOTALL)
    findDate = re.findall(patFinderDate,webpage)
    findArticle = re.findall(patFinderArticle,webpage)

    listIterator = []
    listIterator[:] = range(0,1000)

    for i in listIterator:
        filename = findDate[i]
        with open(filename,"w") as f:
            f.write(i)
            f.close()

1 个答案:

答案 0 :(得分:1)

如果您确定自己拥有与文章一样多的日期,则可以大致重写代码如下:

from urllib import urlopen
import re

webpage = urlopen('x').read()
date_p = re.compile('[0-9]{2}-[a-zA-Z]{3}-[0-9]{4}')
article_p =  re.compile('<span>.*<div>', re.DOTALL)
allDates = re.findall(date_p,webpage)
allArticles = re.findall(article_p,webpage)

for date, article in zip(allDates, allArticles):
    with open(date,"w") as f:
        f.write(article)

zip()函数将两个迭代“拉”成一个并在每次迭代时返回一个2元组 - 这就是你需要检查文章的日期是否与文章一样多的原因