簡體   English   中英

如何將兩個不同列表中的值轉換為單個字典?

[英]How to convert values from two different lists into a single dictionary?

我正在從https://www.investing.com/equities/nvidia-corp-financial-summary中抓取財務摘要。 代碼:

要獲取比率描述:

for element in soup.find_all('span', attrs={'class': 'float_lang_base_1'}):
    print(element)

該代碼將導致:

<span class="float_lang_base_1">Gross margin</span>
<span class="float_lang_base_1">Operating margin</span>
<span class="float_lang_base_1">Net Profit margin</span>
<span class="float_lang_base_1">Return on Investment</span>
<span class="float_lang_base_1">Quick Ratio</span>
<span class="float_lang_base_1">Current Ratio</span>
<span class="float_lang_base_1">LT Debt to Equity</span>
<span class="float_lang_base_1">Total Debt to Equity</span>
<span class="float_lang_base_1">Cash Flow/Share</span>
<span class="float_lang_base_1">Revenue/Share</span>
<span class="float_lang_base_1">Operating Cash Flow</span>

要獲取上述每個比率的值:

for element in soup.find_all('span', attrs={'class': 'float_lang_base_2 text_align_lang_base_2 dirLtr bold'}):
    a = element.get_text()

結果是:

 60.45%
 31.47%
 26.03%
 22.86%
 2.95
 3.62
 -
 49.02%
 -
 -
 16.77%

現在,我需要將兩者進行匹配,這樣它將是一個可以轉換為 dataframe 的鍵值對。

Gross margin : 60.45%
Operating margin: 31.47%
Net Profit margin: 26.03% 
...

您可以使用class和 append 找到具有這兩個值的主div標簽並對其進行迭代以識別其他屬性到dict1

dict1={}
for element in soup.find_all('div', attrs={'class': 'infoLine'}):
    name=element.find("span",class_="float_lang_base_1").get_text()
    value=element.find("span",class_="float_lang_base_2").get_text()
    dict1[name]=value

這里可以使用pandas創建df並將dict1轉換為表格數據

import pandas as pd
df=pd.DataFrame(dict1.items(),columns=['A','B'])
df

Output:

       A                  B
0   Gross margin        60.45%
1   Operating margin    31.47%
.....

您可以將兩個不同列表中的值獲取到單個字典中

Mykeys = ["a", "b", "c"]
Myvalues = [1, 3, 5]
print ("Mykey list: " + str(Mykeys))
print ("Myvalue list: " + str(Myvalues))
res = dict(zip(Mykeys, Myvalues))

print ("New dictionary will be : " +  str(res))

如答案中所述,您可以zip()您的列表並轉換為dict()


無論如何,從元素中選擇和提取信息有一種替代方法:

dict(list(row.stripped_strings)[::len(list(row.stripped_strings))-1] for row in soup.select('.infoLine'))

這將使用 class infoLine select()find_all()元素<span>的容器標記是什么。 雖然.stripped_strings將文本提取為ResultSet我們只需要list slice第一個和最后一個元素並將其在dict comprehension中轉換為最終結果。

請注意:壓縮列表或使用列表,您必須確保它們具有相同的長度,否則您將收到有關此不匹配的錯誤。

例子

import requests
from bs4 import BeautifulSoup
  
url='https://www.investing.com/equities/nvidia-corp-financial-summary'
soup = BeautifulSoup(requests.get(url, headers = {'User-Agent': 'Mozilla/5.0'}).text)
dict(list(row.stripped_strings)[::len(list(row.stripped_strings))-1] for row in soup.select('.infoLine'))

Output

{'Gross margin': '60.45%',
 'Operating margin': '31.47%',
 'Net Profit margin': '26.03%',
 'Return on Investment': '22.86%',
 'Quick Ratio': '2.95',
 'Current Ratio': '3.62',
 'LT Debt to Equity': '-',
 'Total Debt to Equity': '49.02%',
 'Cash Flow/Share': '-',
 'Revenue/Share': '-',
 'Operating Cash Flow': '16.77%'}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM