我有一个字符串,代表一个使用逗号分隔数千个数字的数字。如何在python中将其转换为数字?
>>> int("1,000,000")
生成一个ValueError。
在尝试进行转换之前,我可以将逗号替换为空字符串,但是感觉有点不对劲。有没有更好的办法?
Answers:
import locale
locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' )
locale.atoi('1,000,000')
# 1000000
locale.atof('1,000,000.53')
# 1000000.53
Traceback (most recent call last): File "F:\test\locale_num.py", line 2, in <module> locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) File "F:\Python27\lib\locale.py", line 539, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting
有数千种分隔符可以解析数字。我怀疑@unutbu描述的方式在所有情况下都是最好的。这就是为什么我也列出其他方式。
正确的调用setlocale()位置在__main__模块中。它是全局设置,将影响整个程序甚至C扩展(尽管请注意,LC_NUMERIC设置不是在系统级别设置的,而是由Python模仿的)。阅读文档中的注意事项,然后再三思。在单个应用程序中可能还可以,但是永远不要在图书馆中使用它来吸引广大读者。可能应该避免使用某些特定的字符集编码请求语言环境,因为它在某些系统上可能不可用。
使用第三方库之一进行国际化。例如,PyICU允许使用影响整个过程的任何可用语言环境(甚至使用特定的数千个分隔符来解析数字,而无需使用语言环境):
NumberFormat.createInstance(Locale('en_US'))。parse(“ 1,000,000”)。getLong()
如果您没有安装第三方库来“正确地进行”操作,请编写自己的解析函数。它可以像int(data.replace(',', ''))不需要严格验证时一样简单。
setlocate应为setlocale)。另外,+ 1。
我试过了 它超出了问题:您得到了输入。它将首先转换为字符串(如果它是列表,例如,来自Beautiful soup)。然后是int,然后是float。
它尽其所能。在最坏的情况下,它会将所有未转换的内容返回为字符串。
def to_normal(soupCell):
''' converts a html cell from beautiful soup to text, then to int, then to float: as far as it gets.
US thousands separators are taken into account.
needs import locale'''
locale.setlocale( locale.LC_ALL, 'english_USA' )
output = unicode(soupCell.findAll(text=True)[0].string)
try:
return locale.atoi(output)
except ValueError:
try: return locale.atof(output)
except ValueError:
return output
'C'仍会显示ValueError!)。