用逗号从api中分割数字

  • 本文关键字:分割 数字 api python
  • 更新时间 :
  • 英文 :

import urllib.request, 
urllib.parse, urllib.error
from bs4 import BeautifulSoup
url = "https://api.monzo.com/crowdfunding-investment/total"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract()    # rip it out
# get text
text = soup.get_text()
if 'invested_amount' in text:
result = text.split(",")
invested = str(result[1])
investedn = invested.split(':')[1]
print(investedn)

大家好。我正试图用逗号把investedn分成数千个。有人知道怎么做吗?

另外,如何从字符串中删除最后四个数字?

谢谢!

只需使用

"{:,}".format(number)

https://docs.python.org/3/library/string.html#format-规范迷你语言

例如

In [19]: "{:,}".format(17462233620)
Out[19]: '17,462,233,620'

成功修复!

import urllib.request, urllib.parse, urllib.error
from bs4 import BeautifulSoup
url = "https://api.monzo.com/crowdfunding-investment/total"
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
# kill all script and style elements
for script in soup(["script", "style"]):
script.extract()    # rip it out
# get text
text = soup.get_text()
if 'invested_amount' in text:
result = text.split(",")
invested = str(result[1])
investedn = invested.split(':')[1]
plainnum = int(str(investedn)[:-4])
number = "{:,}".format(int(plainnum))
print(number)

我把事情搞砸了不少,但还是想通了。

谢谢!

您从该URL返回的文本不是HTML。它是以JSON格式编码的数据,易于解析:

import urllib.request
import json
url = "https://api.monzo.com/crowdfunding-investment/total"
json_text = urllib.request.urlopen(url).read()
json_text = json_text.decode('utf-8')
data = json.loads(json_text)
print(data)
print('Invested amount: {:,}'.format(data['invested_amount']))

输出:

{'invested_amount': 17529735495, 'share_price': 77145, 'shares_invested': 227231, 'max_shares': 2592520, 'max_amount': 199999955400, 'status': 'pending'}
Invested amount: 17,529,735,495

票据

  • json_text是一个字节数组,而不是字符串。这就是为什么我使用UTF-8的猜测来解码它
  • data只是一个普通的Python字典
a = "17462233620"
b = ""
for i in range(len(a), 0 , -3):
b = a[i-3:i]+","+b
b = "£" + a[0:i] + b[:-1]
print(b) # Output £17,462,233,620

最新更新