如何将迭代的输出变量捕获到列表中进行分析

时间:2015-06-07 05:09:29

标签: list function python-2.7 parsing sentiment-analysis

我正在尝试解析来自多个网页的html文本以进行情绪分析。在社区的帮助下,我已经能够迭代许多网址,并根据textblob库的情绪分析产生情绪评分,并成功使用打印功能输出每个网址的分数。但是我无法实现,将我的返回变量产生的许多输出放入一个列表中,这样我就可以通过使用存储的数字来计算平均值,并在稍后的图表中显示我的结果,从而进一步继续我的分析。 p>

带打印功能的代码:

import requests
import json
import urllib
from bs4 import BeautifulSoup
from textblob import TextBlob



#you can add to this
urls = ["http://www.thestar.com/business/economy/2015/05/19/canadian-consumer-confidence-dips-but-continues-to-climb-in-us-report.html",
        "http://globalnews.ca/news/2012054/canada-ripe-for-an-invasion-of-u-s-dollar-stores-experts-say/",
        "http://www.cp24.com/news/tsx-flat-in-advance-of-fed-minutes-loonie-oil-prices-stabilize-1.2381931",
        "http://www.marketpulse.com/20150522/us-and-canadian-gdp-to-close-out-week-in-fx/",
        "http://www.theglobeandmail.com/report-on-business/canada-pension-plan-fund-sees-best-ever-annual-return/article24546796/",
        "http://www.marketpulse.com/20150522/canadas-april-inflation-slowest-in-two-years/"]


def parse_websites(list_of_urls):
    for url in list_of_urls:
        html = urllib.urlopen(url).read()
        soup = BeautifulSoup(html)
        # kill all script and style elements

        for script in soup(["script", "style"]):
            script.extract()    # rip it out

        # get text
        text = soup.get_text()

        # break into lines and remove leading and trailing space on each
        lines = (line.strip() for line in text.splitlines())
        # break multi-headlines into a line each
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        # drop blank lines
        text = '\n'.join(chunk for chunk in chunks if chunk)

        #print(text)

        wiki = TextBlob(text)
        r = wiki.sentiment.polarity

        print r




parse_websites(urls)

输出:

>>> 
0.10863027172
0.156074203574
0.0766585497835
0.0315555555556
0.0752548359411
0.0902824858757
>>> 

但是当我使用return变量形成一个列表来使用值来处理时,我得不到结果,代码:

import requests
import json
import urllib
from bs4 import BeautifulSoup
from textblob import TextBlob



#you can add to this
urls = ["http://www.thestar.com/business/economy/2015/05/19/canadian-consumer-confidence-dips-but-continues-to-climb-in-us-report.html",
        "http://globalnews.ca/news/2012054/canada-ripe-for-an-invasion-of-u-s-dollar-stores-experts-say/",
        "http://www.cp24.com/news/tsx-flat-in-advance-of-fed-minutes-loonie-oil-prices-stabilize-1.2381931",
        "http://www.marketpulse.com/20150522/us-and-canadian-gdp-to-close-out-week-in-fx/",
        "http://www.theglobeandmail.com/report-on-business/canada-pension-plan-fund-sees-best-ever-annual-return/article24546796/",
        "http://www.marketpulse.com/20150522/canadas-april-inflation-slowest-in-two-years/"]


def parse_websites(list_of_urls):
    for url in list_of_urls:
        html = urllib.urlopen(url).read()
        soup = BeautifulSoup(html)
        # kill all script and style elements

        for script in soup(["script", "style"]):
            script.extract()    # rip it out

        # get text
        text = soup.get_text()

        # break into lines and remove leading and trailing space on each
        lines = (line.strip() for line in text.splitlines())
        # break multi-headlines into a line each
        chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
        # drop blank lines
        text = '\n'.join(chunk for chunk in chunks if chunk)

        #print(text)

        wiki = TextBlob(text)
        r = wiki.sentiment.polarity
        r = []
        return [r]




parse_websites(urls)

输出:

Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> ================================ RESTART ================================
>>> 
>>> 

我怎样才能做到这一点,我可以使用这些数字,并能够从列表中添加,减去它们,如[r1,r2,r3 ...]

提前谢谢你。

1 个答案:

答案 0 :(得分:1)

从下面的代码中,您要求python返回一个空列表:

r = wiki.sentiment.polarity

r = []     #creat empty list r
return [r] #return empty list

如果我理解你的问题,你所要做的就是:

my_list = [] #create empty list

   for url in list_of_urls:
    html = urllib.urlopen(url).read()
    soup = BeautifulSoup(html)

    for script in soup(["script", "style"]):
        script.extract()    # rip it out

    text = soup.get_text()

    lines = (line.strip() for line in text.splitlines())
    chunks = (phrase.strip() for line in lines for phrase in line.split("  "))
    text = '\n'.join(chunk for chunk in chunks if chunk)

    wiki = TextBlob(text)
    r = wiki.sentiment.polarity

    my_list.append(r) #add r to list my_list

print my_list
  

[r1,r2,r3,...]

或者,您可以创建一个以url作为键

的字典
my_dictionary = {}

        r = wiki.sentiment.polarity
        my_dictionary[url] = r

print my_dictionary
  

{' url1':r1,' url2:r2等)

print my_dictionary['url1']
  

R1

字典对您来说可能更有意义,因为使用用作密钥的网址会更容易检索,编辑和删除" r"

我对Python很陌生,所以希望其他人会纠正我,如果这没有意义......