我如何始终如一地转换诸如"3.71B"之类的字符串?和"4M"到Python中的数字? [英] How can I consistently convert strings like "3.71B" and "4M" to numbers in Python?

查看:100
本文介绍了我如何始终如一地转换诸如"3.71B"之类的字符串?和"4M"到Python中的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些代码比较混乱,几乎可以从Yahoo Finance为公司生成有形价格/帐簿(一个名为ystockquote的不错的模块可以得到无形价格/帐簿值).

I have some rather mangled code that almost produces the tangible price/book from Yahoo Finance for companies (a nice module called ystockquote gets the intangible price/book value already).

我的问题是这样

对于计算中的一个变量,流通股,我得到的字符串如 10.89B 4.9M ,其中 B M 分别代表十亿百万.我在将它们转换为数字时遇到麻烦,这是我的位置:

For one of the variables in the calculation, shares outstanding I'm getting strings like 10.89B and 4.9M, where B and M stand respectively for billion and million. I'm having trouble converting them to numbers, here's where I'm at:

shares=''.join(node.findAll(text=True)).strip().replace('M','000000').replace('B','000000000').replace('.','') for node in soup2.findAll('td')[110:112]

这很凌乱,但是我认为,如果不是,

Which is pretty messy, but I think it would work if instead of

.replace('M','000000').replace('B','000000000').replace('.','') 

我正在使用带变量的正则表达式.我想问题很简单,就是哪个正则表达式和变量.其他建议也很好.

I was using a regular expression with variables. I guess the question is simply which regular expression and variables. Other suggestions are also good.

具体来说,我希望对零,一或两个小数的数字都适用,但是这些答案看起来都很有帮助.

To be specific I'm hoping to have something that works for numbers with zero, one, or two decimals but these answers all look helpful.

推荐答案

>>> from decimal import Decimal
>>> d = {
        'M': 6,
        'B': 9
}
>>> def text_to_num(text):
        if text[-1] in d:
            num, magnitude = text[:-1], text[-1]
            return Decimal(num) * 10 ** d[magnitude]
        else:
            return Decimal(text)

>>> text_to_num('3.17B')
Decimal('3170000000.00')
>>> text_to_num('4M')
Decimal('4000000')
>>> text_to_num('4.1234567891234B')
Decimal('4123456789.1234000000000')

如果需要,也可以int()结果

这篇关于我如何始终如一地转换诸如"3.71B"之类的字符串?和"4M"到Python中的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆