在Python 3中将str显式转换为float

时间:2016-02-23 04:41:50

标签: python casting typeerror

我正在接受" TypeError:无法转换'浮动'反对str含义"错误,因为我试图用字符串划分浮点数。

我正在尝试将字符串转换为浮点数,但仍然出现错误。

字符串' empNumber'是所有数字,但有一个逗号(例如:112,000) - 因此"替换"用于去除逗号的函数。当我尝试划分" final / decimal"时,我正在画一个错误。如何修复此类错误?

def revPerEmployee():
    for ticker in sp500short:
        searchurl = "http://finance.yahoo.com/q/ks?s="+ticker
        f = urlopen(searchurl)
        html = f.read()
        soup = BeautifulSoup(html, "html.parser")

        searchurlemp = "http://finance.yahoo.com/q/pr?s="+ticker+"+Profile"
        femp = urlopen(searchurlemp)
        htmlemp = femp.read()
        soupemp = BeautifulSoup(htmlemp, "html.parser")

        try:
            revenue2 = soup.find("td", text="Revenue (ttm):").find_next_sibling("td").text
            empCount2 = soupemp.find("td", text="Full Time Employees:").find_next_sibling("td").text 

        except:
            revenue2 = "There is no data for this company"
            empCount2 = "There is no data for this company"         

        if revenue2 == "There is no data for this company" or empCount2 == "There is no data for this company":
            lastLetter = ticker+": There is no data for this company"
        else:
            lastLetter = revenue2[len(revenue2)-1:len(revenue2)]
            empNumber = empCount2.replace(",", "")
            decimal = float(empNumber)

        if lastLetter == "B":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000000000.0
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        elif lastLetter == "M":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000000.0
            #newnum = "{:0,.2f}".format(final)
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        elif lastLetter == "K":
            result = revenue2[:-1]
            revNum = float(result)
            final = revNum * 1000.0
            #newnum = "{:0,.2f}".format(final)
            revPerEmp = final/decimal
            print(ticker+": "+revPerEmp)

        else:
            print(lastLetter)

2 个答案:

答案 0 :(得分:3)

17 + "orange"是无稽之谈,您无法添加数字和字符串。你想要

print("%s: %s" % (ticker, revPerEmp))

(您可以将%s切换为其他格式,例如%.2f)或

print(str(ticker) + ": " + str(revPerEmp))

答案 1 :(得分:1)

问题在于,您的程序假定从URL请求获得的是数字形式的数字,后跟后缀(K,M或B)。这未经过测试。

还有两个改进代码的建议。首先,您使用try ... except子句来检查何时无法获取数据。如果转换失败,您也可以使用它。消息"该公司没有数据"可以在except子句中打印。

其次,你有三个if条款非常相似,暗示它们可以被浓缩。 python字典可用于后缀值。

SUFFIX_VALUES = { 'K': 1000.0, 'M': 1000000.0, 'B': 1000000000.0 }
try:
  # taken from your code
  revenue2 = soup.find("td", text="Revenue(ttm):").find_next_sibling("td").text
  empCount2 = soupemp.find("td", text="Full Time Employees:").find_next_sibling("td").text 
  revNum = float(revenue2[:-1])
  empNumber = empCount2.replace(",", "")
  decimal = float(empNumber)
  lastLetter = revenue2[-1]
  final = revNum * SUFFIX_VALUES[lastLetter]
  revPerEmp = final/decimal
  print("%s: %d" % (ticker, revPerEmp))
except:
  print(ticker + ": There is no data for this company")

现在,如果URL请求中缺少数据,如果转换失败,或者后缀错误,程序将执行except子句。