繁体   English   中英

如何从python中的文本中提取数字?

[英]How to extract number from text in python?

我有下面列出的字符串

str = ['"Consumers_Of_Product": {"count": 13115}']

我如何提取数字 13115,因为它会改变,以便它始终等于 var。 换句话说,我如何从这个字符串中提取这个数字?

我以前做过的大多数事情都没有奏效,我认为这是由于语法。 我正在运行 Python 2.7。

如果您只想提取该数字,前提是该字符串中没有其他数字, regex可以使用regex 由于@TigerhawkT3 回答中提到的原因,我将str重命名为s

import re
s = ['"Consumers_Of_Product": {"count": 13115}']
num = re.findall('\d+', s[0])
print(num[0])
13115

在该列表中的单个元素上使用ast.literal_eval (您不应该调用str因为它掩盖了内置元素,并且无论如何它都不是字符串),在花括号内(因为它似乎是一个字典元素) :

>>> import ast
>>> s = ['"Consumers_Of_Product": {"count": 13115}']
>>> ast.literal_eval('{{{}}}'.format(s[0]))
{'Consumers_Of_Product': {'count': 13115}}

你有3个选择

但是推荐使用json lib

import json
s = ['"Consumers_Of_Product": {"count": 13115}']
s[0] = '{' + s[0] + '}'
my_var = json.loads(s[0]) # this is where you translate from string to dict
print my_var['Consumers_Of_Product']['count']
# 13115

记住TigerhawkT3所说的为什么不应该使用str

您可以使用regular expression从字符串中提取任何您想要的内容。 这是关于如何在 python 中使用正则表达式的链接

示例代码在这里:

import re
m = re.search(r'(\d+)', s[0])
if m:
    print m.group()
else:
    print 'nothing found'

你的字符串看起来像一个JSON字符串,所以如果你正在处理 json 字符串,你可以使用json包来提取字段count的值

此处的示例代码(您需要用{}或数组[]包裹您的字符串):

import json
obj = json.loads('{"Consumers_Of_Product": {"count": 13115}}')
print(obj['Consumers_Of_Product']['count'])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM