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)
大家好。我正在尝试用逗号将投资分成几千个。有人知道该怎么做吗?
另外,如何从字符串中删除最后四个数字?
谢谢!
答案 0 :(得分:1)
只需使用
"{:,}".format(number)
https://docs.python.org/3/library/string.html#format-specification-mini-language
例如
In [19]: "{:,}".format(17462233620)
Out[19]: '17,462,233,620'
答案 1 :(得分:0)
设法解决!
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)
我搞砸了很多,但是弄明白了。
谢谢!
答案 2 :(得分:0)
从该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字典。答案 3 :(得分:-1)
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