簡體   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