最近我決定做一個快速的網頁抓取和資料分析專案。因為我的大腦喜歡想出需要花費大量時間的大想法,所以我決定挑戰自己,想出一些可以在幾個小時內完成的簡單事情。
這是我想到的:
由於我的本科學位最初是外語(法語和西班牙語),我認為網絡抓取一些語言相關數據會很有趣。我想使用 BeautifulSoup 庫,它可以解析靜態 html,但無法處理需要 onclick 事件來顯示整個資料集的動態網頁(即,如果頁面已分頁,則單擊下一頁資料)。
我決定使用最常用語言的維基百科頁面。
我想做以下事情:
- 取得頁面的 html 並輸出到 .txt 檔案
- 使用beautiful soup解析html檔案並擷取表格資料
- 將表格寫入 .csv 檔案
- 使用資料分析提出我想回答此資料集的 10 個問題
- 用 pandas 和 Jupyter Notebook 回答這些問題
我決定將專案分成這些步驟以分離關注點,但我也想避免透過重新運行腳本來發出多個不必要的請求以從維基百科獲取 html。保存 html 文件,然後在單獨的腳本中使用它意味著您不需要不斷重新請求數據,因為您已經擁有了數據。
項目連結
此專案的 github 儲存庫的連結為:https://github.com/gabrielrowan/Foreign-Languages-Analysis
取得html
首先,我檢索並輸出 html。使用 C# 和 C 後,我總是對 Python 程式碼如此簡短和簡潔感到新奇?
url = 'https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers' response = requests.get(url) html = response.text with open("languages_html.txt", "w", encoding="utf-8") as file: file.write(html)
解析 html
為了用 Beautiful soup 解析 html 並選擇我感興趣的表,我做了:
with open("languages_html.txt", "r", encoding="utf-8") as file: soup = BeautifulSoup(file, 'html.parser') # get table top_languages_table = soup.select_one('.wikitable.sortable.static-row-numbers')
然後,我取得了表格標題文字來取得 pandas 資料框的列名稱:
# get column names columns = top_languages_table.find_all("th") column_titles = [column.text.strip() for column in columns]
之後,我建立了資料框,設定列名稱,檢索每個表格行並將每一行寫入資料框:
# get table rows table_data = top_languages_table.find_all("tr") # define dataframe df = pd.DataFrame(columns=column_titles) # get table data for row in table_data[1:]: row_data = row.find_all('td') row_data_txt = [row.text.strip() for row in row_data] print(row_data_txt) df.loc[len(df)] = row_data_txt
注意 - 不使用 strip() 時,文字中有 n 個不需要的字元。
最後,我將資料幀寫入 .csv。
分析數據
事先,我從數據中提出了我想回答的這些問題:
- 資料集中所有語言的母語總數是多少?
- 有多少種不同類型的語系?
- 每個語系的母語總數是多少?
- 最常用的 3 個語係是什麼?
- 建立一個圓餅圖,顯示最常用的 3 個語系
- 最常見的語系-分支對是什麼?
- 表中哪些語言屬於漢藏語系?
- 顯示所有羅曼語系和日耳曼語系語言的母語人士的長條圖
- 前 5 種語言佔母語使用者總數的百分比是多少?
- 哪個分支的母語使用者最多,哪個分支最少?
結果
雖然我不會透過程式碼來回答所有這些問題,但我會討論涉及圖表的兩個問題。
顯示所有羅曼語和日耳曼語母語的長條圖
首先,我建立了一個資料框,僅包含分支名稱為「Romance」或「Germanic」的行
url = 'https://en.wikipedia.org/wiki/List_of_languages_by_number_of_native_speakers' response = requests.get(url) html = response.text with open("languages_html.txt", "w", encoding="utf-8") as file: file.write(html)
然後我指定了圖表的 x 軸、y 軸和條形顏色:
with open("languages_html.txt", "r", encoding="utf-8") as file: soup = BeautifulSoup(file, 'html.parser') # get table top_languages_table = soup.select_one('.wikitable.sortable.static-row-numbers')
這創建了:
建立一個圓餅圖,顯示 3 個最常用的語系
為了建立圓餅圖,我檢索了最常見的 3 個語系並將它們放入資料框中。
此代碼組取得每個語系的母語人士總數,按降序排序,並提取前 3 個條目。
# get column names columns = top_languages_table.find_all("th") column_titles = [column.text.strip() for column in columns]
然後我將資料放入圓餅圖中,指定「母語者」的 y 軸和圖例,這為圖表中顯示的每個語言系列建立顏色編碼標籤。
# get table rows table_data = top_languages_table.find_all("tr") # define dataframe df = pd.DataFrame(columns=column_titles) # get table data for row in table_data[1:]: row_data = row.find_all('td') row_data_txt = [row.text.strip() for row in row_data] print(row_data_txt) df.loc[len(df)] = row_data_txt
其餘問題的程式碼和答案可以在這裡找到。我在筆記本中使用 Markdown 寫下問題及其答案。
下次:
對於我的網頁抓取和資料分析專案的下一個迭代,我想讓事情變得更複雜:
- 網頁抓取動態頁面,點擊/捲動時會顯示更多資料
- 分析較大的資料集,可能需要在分析之前進行一些資料清理工作
最後的想法
儘管速度很快,但我很喜歡做這個專案。它提醒我,簡短、可管理的專案對於讓練習代表參與其中有多有用?另外,從互聯網提取數據並從中創建圖表,即使數據集很小,也很有趣?
以上是網路抓取與分析外語數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Python是解釋型語言,但也包含編譯過程。 1)Python代碼先編譯成字節碼。 2)字節碼由Python虛擬機解釋執行。 3)這種混合機制使Python既靈活又高效,但執行速度不如完全編譯型語言。

UseeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.forloopsareIdealForkNownsences,而WhileLeleLeleLeleLeleLoopSituationSituationsItuationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐個偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供應模擬性和可讀性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

SecLists
SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

Dreamweaver CS6
視覺化網頁開發工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1
好用且免費的程式碼編輯器