将函数写入单独的文本文件?

时间:2015-09-23 18:47:24

标签: function python-2.7 web-scraping beautifulsoup

我正在运行一些网页抓取,现在已经保存了以下保存的911个链接列表(我包含了5个以展示它们是如何存储的):

every_link = ['http://www.millercenter.org/president/obama/speeches/speech-4427', 'http://www.millercenter.org/president/obama/speeches/speech-4425', 'http://www.millercenter.org/president/obama/speeches/speech-4424', 'http://www.millercenter.org/president/obama/speeches/speech-4423', 'http://www.millercenter.org/president/obama/speeches/speech-4453']

这些网址会随着时间的推移链接到总统演讲。我想将每个单独的演讲(所以,911个独特的演讲)存储在不同的文本文件中,或者能够按总统分组。我正在尝试将以下函数传递给这些链接:

def processURL(l):
    open_url = urllib2.urlopen(l).read()
    item_soup = BeautifulSoup(open_url)
    item_div = item_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
    item_str = item_div.text.lower()
    item_str_processed = punctuation.sub('',item_str)
    item_str_processed_final = item_str_processed.replace('—',' ')

for l in every_link:
    processURL(l)

所以,我想要保存所有已处理的演讲中的唯一文本文件字。这可能如下所示,obama_44xx表示单个文本文件:

obama_4427 = "blah blah blah"
obama_4425 = "blah blah blah"
obama_4424 = "blah blah blah"
...

我正在尝试以下方法:

for l in every_link:
    processURL(l)
    obama.write(processURL(l))

但这不起作用...... 还有其他方法可以解决这个问题吗?

2 个答案:

答案 0 :(得分:1)

好的,所以你有几个问题。首先,您的processURL函数实际上并没有返回任何内容,因此当您尝试编写函数的返回值时,它将成为None。也许尝试这样的事情:

def processURL(link):
    open_url = urllib2.urlopen(link).read()
    item_soup = BeautifulSoup(open_url)
    item_div = item_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
    item_str = item_div.text.lower()
    item_str_processed = punctuation.sub('',item_str)
    item_str_processed_final = item_str_processed.replace('—',' ')

    splitlink = link.split("/")
    president = splitlink[4]
    speech_num = splitlink[-1].split("-")[1]
    filename = "{0}_{1}".format(president, speech_num)

    return filename, item_str_processed_final # returning a tuple

for link in every_link:
    filename, content = processURL(link) # yay tuple unpacking
    with open(filename, 'w') as f:
        f.write(content)

这会将每个文件写入一个看起来像president_number的文件名。例如,它会将身份证号码为4427的奥巴马的演讲写入名为obama_4427的文件中。 Lemme知道这是否有效!

答案 1 :(得分:1)

您必须调用processURL函数并让它返回您想要写入的文本。之后,您只需在循环中添加写入磁盘代码。像这样:

def processURL(l):
    open_url = urllib2.urlopen(l).read()
    item_soup = BeautifulSoup(open_url)
    item_div = item_soup.find('div',{'id': 'transcript'},{'class': 'displaytext'})
    item_str = item_div.text.lower()
    #item_str_processed = punctuation.sub('',item_str)
    #item_str_processed_final = item_str_processed.replace('—',' ')
    return item_str

for l in every_link:
    speech_text = processURL(l).encode('utf-8').decode('ascii', 'ignore')
    speech_num = l.split("-")[1]
    with open("obama_"+speech_num+".txt", 'w') as f:
        f.write(speech_text)

.encode('utf-8').decode('ascii', 'ignore')纯粹是为了处理文本中的非ascii字符。理想情况下,您会以不同的方式处理它们,但这取决于您的需求(请参阅Python: Convert Unicode to ASCII without errors)。

顺便说一句,你列表中的第二个链接是404.你应该确保你的脚本可以处理它。

相关问题