整数,浮和美丽的汤

2024-06-29 00:47:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将我的所有的数据标签转换成一种格式,这样我就可以用布尔值与它们进行比较。我认为它涉及到使用float和/或int运算符。不过,我有一些担心的输出一旦网站被废弃。输出以整数、小数和百分比表示。我要修改的具体行是第33行。我尝试过使用int()和.int。在Stackoverflow上或在Beautiful Soup文档中都没有发现任何问题。在

from BeautifulSoup import BeautifulSoup
import csv
import re
import urllib
import urllib2
from urllib2 import HTTPError
# import modules

symbolfile = open("symbols.txt")
symbolslist = symbolfile.read()
newsymbolslist = symbolslist.split("\n")

i = 0

f = csv.writer(open("pe_ratio.csv","wb"))
# short cut to write

f.writerow(["Name","PE","Revenue % Quarterly","ROA% YOY","Operating Cashflow","Debt to Equity"])
#first write row statement

# define name_company as the following
while i<len(newsymbolslist):
    try:
        page = urllib2.urlopen("http://finance.yahoo.com/q/ks?s="+newsymbolslist[i] +"%20Key%20Statistics").read()
    except urllib2.HTTPError:
        continue
    soup = BeautifulSoup(page)
    name_company = soup.findAll("div", {"class" : "title"}) 
    for name in name_company: #add multiple iterations?        
        all_data = soup.findAll('td', "yfnc_tabledata1")
        stock_name = name.find('h2').string #find company's name in name_company with h2 tag
        try:    
            f.writerow([stock_name, all_data[2].getText(),all_data[17].getText(),all_data[13].getText(), all_data[29].getText(),all_data[26].getText()]) #write down PE data
        except (IndexError, HTTPError) as e:
            pass
    i+=1    

这就是CSV文件中的输出。在

^{pr2}$

请记住,您将股票代码垂直放置在符号.txt文件。在


Tags: csvnamefromimportdataallurllib2company
2条回答

要将all\U数据字符串值转换为数字,请尝试如下操作:

all_data = soup.findAll('td', "yfnc_tabledata1")
stock_name = name.find('h2').string #find company's name in name_company with h2 tag

clean_data = list()
for x in [data.GetText().strip(' %') for data in all_data]
    try: 
        clean_data.append(float(x))
    except ValueError:
        clean_data.append(x)

try:    
    f.writerow([stock_name, clean_data[2], clean_data[17], clean_data[13], clean_data[29], clean_data[26]]) #write down PE data
except (IndexError, HTTPError) as e:
        pass

如果要对数据进行比较(即季度百分比大于25),则必须格式化文本以便将其转换为数字

quarterly_percent = all_data[17].getText()
if quarterly_percent != "N/A":
    #cut off the percent sign and conver to a "python number"
    quarterly_percent = float(quarterly_percent[:-1])
    if quarterly_percent > 25:
        print "its a good one"

相关问题 更多 >