[英]Extracting numbers from python vars
基本上我正在抓取一個網站並將結果保存在一個 var 中。 假設我的代碼中有這個:
worldPopulation = [scraping and such]
現在“worldPopulation”變量具有以下內容:
545.452.432.675
世界總人口
注意:在 var 的上方和下方都有一個空白行。 所以2行充滿了空白。
我一直在嘗試提取數字並將它們解析到 SQLite3 數據庫。 我使用 INT 作為數據類型,我試過這個:
re.findall(r'\b\d+\b', worldPopulation)
並且
re.findall(r'\d+', worldPopulation)
兩者都給了我錯誤,它們是:
Line 241, in find all
return _compile(pattern, flags).findall(string)
TypeError: expected string or bytes-like object
有誰知道如何從變量中檢索該數字? 它以百萬為單位,所以我真的不想將這個數字分成 4 組 3 個數字,只是想要它作為一個整體。
以下內容應該可以幫助您:
import re
worldPopulation = '545.452.432.675 Worlds Total Population'
worldPopulation_number = int(re.sub('[a-zA-Z. ]','',worldPopulation))
如果您要查找的是分開的數字。 這可能會幫助您:
import re
worldPopulation = '545.452.432.675 Worlds Total Population'
worldPopulation_numbers = [int(x) for x in re.sub('[a-zA-Z ]','',worldPopulation).split('.')]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.