【问题标题】:How to capture iterated output variable into list for analysis如何将迭代的输出变量捕获到列表中进行分析
【发布时间】:2015-06-07 05:09:29
【问题描述】:

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

带打印功能的代码:

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
>>> 

但是当我使用返回变量形成一个列表来使用这些值时,我没有得到任何结果,代码:

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...] 从列表中添加、减去它们

提前谢谢你。

【问题讨论】:

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


    【解决方案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, etc)

    print my_dictionary['url1']
    

    r1

    字典可能对您更有意义,因为使用用作键的 url 会更容易检索、编辑和删除“r”。

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

    【讨论】:

    • 感谢您的快速回复!我只希望输出在一个列表中,并且效果很好。
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    • 1970-01-01
    • 2011-12-27
    • 2019-04-10
    相关资源
    最近更新 更多