[英]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.