
來源:早起Python
作者:陳熹
大家好,我是早起。
在之前的文章 批量翻譯文檔 中,我們介紹了如何調(diào)用百度翻譯API完成實(shí)際的文檔翻譯需求。如果是科研、深度學(xué)習(xí)等需要經(jīng)常閱讀大量論文的工作,批量翻譯就能大大提高效率。
本文將進(jìn)一步使用 Python 實(shí)現(xiàn)另一個在科研學(xué)術(shù)領(lǐng)域的辦公自動化應(yīng)用?!?/span>結(jié)合爬蟲批量翻譯文獻(xiàn)題目和摘要,并存儲搜索和翻譯結(jié)果至 Excel中」
完成效果如下,指定的外文文獻(xiàn)標(biāo)題、摘要都被批量翻譯后存儲在Excel中,我們可以大致瀏覽后有選擇性的挑選文章閱讀!
本文以ACM協(xié)會的文獻(xiàn)為例,搜索的關(guān)鍵詞是 “對抗生成網(wǎng)絡(luò)+眼底” ,即 “GAN+fundus”
本文需求可以看做三塊內(nèi)容:爬蟲+翻譯+存儲 在使用百度的通用翻譯 API 之前需要完成以下工作:
“使用百度賬號登錄百度翻譯開放平臺(
http://api.fanyi.baidu.com)注冊成為開發(fā)者,獲得APPID;進(jìn)行開發(fā)者認(rèn)證(如僅需標(biāo)準(zhǔn)版可跳過);開通通用翻譯API服務(wù):開通鏈接參考技術(shù)文檔和Demo編寫代碼”
完成后在個人頁面在即可看到 ID 和密鑰,這個很重要!
關(guān)于如何使用Python爬取翻譯結(jié)果的細(xì)節(jié)本文就不再贅述!我已經(jīng)將通用翻譯 API 的 demo代碼寫好,已經(jīng)對輸出做簡單修改,拿走就能用!
import requests import random import json from hashlib import md5 # Set your own appid/appkey. appid = 'xxx' appkey = 'xxx' # For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21` from_lang = 'en' to_lang = 'zh' endpoint = 'http://api.fanyi.baidu.com' path = '/api/trans/vip/translate' url = endpoint + path
query = 'Hello World! This is 1st paragraph.nThis is 2nd paragraph.' # Generate salt and sign def make_md5(s, encoding='utf-8'): return md5(s.encode(encoding)).hexdigest()
salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey) # Build request headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign} # Send request r = requests.post(url, params=payload, headers=headers)
result = r.json() # Show response for res in result['trans_result']:
print(res['dst'])
在本需求中可以考慮將上面的API重新包裝成函數(shù),將爬取的題目和摘要看做兩個文本輸入函數(shù)后,返回翻譯的結(jié)果:
import requests import random import json from hashlib import md5 def make_md5(s, encoding='utf-8'): return md5(s.encode(encoding)).hexdigest() def Baidu_translate(query): # Set your own appid/appkey. appid = 'xxx' appkey = 'xxx' from_lang = 'en' to_lang = 'zh' endpoint = 'http://api.fanyi.baidu.com' path = '/api/trans/vip/translate' url = endpoint + path
try:
salt = random.randint(32768, 65536)
sign = make_md5(appid + query + str(salt) + appkey)
# Build request headers_new = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
# Send request r = requests.post(url, params=payload, headers=headers_new)
result = r.json()['trans_result'][0]['dst']
return result
except:
return '翻譯出錯'
函數(shù)中用 try 捕獲錯誤避免中途因?yàn)樘峤坏奈谋緸榭?,而?dǎo)致的報(bào)錯終止程序
存儲部分,通過 openpyxl 或者 xlwings 存儲到 Excel 中就可以
爬蟲部分,兩個網(wǎng)站的邏輯非常類似,具體見下文
首先爬取ACM的摘要,在首頁搜索框中輸入:GAN+fundus 跳轉(zhuǎn)后可以發(fā)現(xiàn),URL包含了關(guān)鍵詞:
那么后面的搜索就可以直接用URL拼接:
keyword = 'GAN+fundus' url_init = r'https://dl.acm.org/action/doSearch?AllField=' url =url_init + keyword
搜索結(jié)果非常多,本文爬取第一頁文章的摘要為例,后續(xù)讀者當(dāng)關(guān)鍵詞鎖定的文獻(xiàn)比較少或者想獲取全部文獻(xiàn),可以自行尋找URL翻頁邏輯
同時我們發(fā)現(xiàn),摘要顯示不全,確認(rèn)源代碼和ajax動態(tài)加載不包含完整摘要,因此可以考慮進(jìn)入各文獻(xiàn)的詳情頁獲取摘要:
回到搜索結(jié)果頁,對詳情頁分析可以發(fā)現(xiàn)每個文獻(xiàn)可獲取的href跟 dl.acm.org 拼接后即為詳情頁URL:
接下來就可以利用Xpath獲取搜索頁第一頁全部文獻(xiàn)的 href 并拼接成新URL:
import requests from lxml import html
keyword = 'GAN+fundus' url_init = r'https://dl.acm.org/action/doSearch?AllField=' url =url_init + keyword
html_data = requests.get(url).text
selector = html.fromstring(html_data)
articles = selector.xpath('//*[@id="pb-page-content"]/div/main/div[1]/div/div[2]/div/ul/li') for article in articles:
url_new = 'https://dl.acm.org' + article.xpath('div[2]/div[2]/div/h5/span/a/@href')[0]
print(url_new)
獲得新的URL之后,重新用Xpath解析新的網(wǎng)頁獲取題目和摘要:
for article in articles:
url_new = 'https://dl.acm.org' + article.xpath('div[2]/div[2]/div/h5/span/a/@href')[0]
html_data_new = requests.get(url_new).text
selector_new = html.fromstring(html_data_new)
title = selector_new.xpath('//*[@id="pb-page-content"]/div/main/div[2]/article/div[1]/div[2]/div/div[2]/h1/text()')[0]
abstract = selector_new.xpath('//div[@class="abstractSection abstractInFull"]/p/text()')[0]
print('Title: ' + title)
print('Abstract: ' + abstract)
print('-' * 20)
題目和摘要可以成功輸出,但現(xiàn)在還是英文形式。只需要將文本提交給上文中包裝好的翻譯函數(shù),輸出返回值就是中文翻譯形式了。注意免費(fèi)的API每秒只允許調(diào)用一次,可以考慮將題目和摘要組合成一個文本同時提交,或者中間休眠一秒:
for article in articles:
url_new = 'https://dl.acm.org' + article.xpath('div[2]/div[2]/div/h5/span/a/@href')[0]
html_data_new = requests.get(url_new).text
selector_new = html.fromstring(html_data_new)
title = selector_new.xpath('//*[@id="pb-page-content"]/div/main/div[2]/article/div[1]/div[2]/div/div[2]/h1/text()')[0]
abstract = selector_new.xpath('//div[@class="abstractSection abstractInFull"]/p/text()')[0]
title = 'Title: ' + title
translated_title = Baidu_translate(title)
print(title)
print(translated_title)
time.sleep(1)
abstract = 'Abstract: ' + abstract translated_abstract = Baidu_translate(abstract)
print(abstract)
print(translated_abstract)
time.sleep(1)
print('-' * 20)
題目和摘要成功翻譯!接下來可以自定義對接意向的持久化存儲了,以openpyxl為例,首先在代碼的開頭用 openpyxl 創(chuàng)建 Excel 文件并寫入表頭:
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
header = ['序號', '題目', '題目(譯)', '摘要', '摘要(譯)']
sheet.append(header)
path = 'xxx' # 希望保存文件的路徑
用變量 num 標(biāo)記文章的順序,并在每篇文章解析和翻譯完后利用 sheet.append(list) 寫入 Excel,循環(huán)結(jié)束后保存文件即完成全部存儲:
num = 0 keyword = 'GAN+fundus' url_init = r'https://dl.acm.org/action/doSearch?AllField=' url =url_init + keyword
html_data = requests.get(url).text
selector = html.fromstring(html_data)
articles = selector.xpath('//*[@id="pb-page-content"]/div/main/div[1]/div/div[2]/div/ul/li') for article in articles:
num += 1 url_new = 'https://dl.acm.org' + article.xpath('div[2]/div[2]/div/h5/span/a/@href')[0]
html_data_new = requests.get(url_new).text
selector_new = html.fromstring(html_data_new)
title = selector_new.xpath('//*[@id="pb-page-content"]/div/main/div[2]/article/div[1]/div[2]/div/div[2]/h1/text()')[0]
abstract = selector_new.xpath('//div[@class="abstractSection abstractInFull"]/p/text()')[0]
title = 'Title: ' + title
translated_title = Baidu_translate(title)
print(title)
print(translated_title)
time.sleep(1)
abstract = 'Abstract: ' + abstract
translated_abstract = Baidu_translate(abstract)
print(abstract)
print(translated_abstract)
time.sleep(1)
print('-' * 20)
sheet.append([num, title, translated_title, abstract, translated_abstract])
wb.save(path + r'文獻(xiàn)輸出.xlsx')
最終實(shí)現(xiàn)效果如下,可以看到指定的文章標(biāo)題、摘要都被翻譯提取出來,我們可以大致瀏覽后有選擇的查閱文章。
另外還有一個重要的計(jì)算機(jī)協(xié)會,IEEE(https://ieeexplore.ieee.org/Xplore/home.jsp),網(wǎng)頁信息爬取邏輯和ACM非常類似,不再贅述
綜合各種辦公自動化技術(shù),我們可以實(shí)現(xiàn)各式各樣的辦公或科研需求,扎實(shí)的技術(shù)是最重要的前提。
例如本文的需求,其實(shí)我們還可以通過 openpyxl 或者 xlwings 存儲到 Excel 中,實(shí)際上還可以 python-docx 寫入 Word 中,甚至從文獻(xiàn)中獲取圖片,借助 python-pptx 寫入 PPT 中。
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
SQL Server 中 CONVERT 函數(shù)的日期轉(zhuǎn)換:從基礎(chǔ)用法到實(shí)戰(zhàn)優(yōu)化 在 SQL Server 的數(shù)據(jù)處理中,日期格式轉(zhuǎn)換是高頻需求 —— 無論 ...
2025-09-18MySQL 大表拆分與關(guān)聯(lián)查詢效率:打破 “拆分必慢” 的認(rèn)知誤區(qū) 在 MySQL 數(shù)據(jù)庫管理中,“大表” 始終是性能優(yōu)化繞不開的話題。 ...
2025-09-18CDA 數(shù)據(jù)分析師:表結(jié)構(gòu)數(shù)據(jù) “獲取 - 加工 - 使用” 全流程的賦能者 表結(jié)構(gòu)數(shù)據(jù)(如數(shù)據(jù)庫表、Excel 表、CSV 文件)是企業(yè)數(shù)字 ...
2025-09-18DSGE 模型中的 Et:理性預(yù)期算子的內(nèi)涵、作用與應(yīng)用解析 動態(tài)隨機(jī)一般均衡(Dynamic Stochastic General Equilibrium, DSGE)模 ...
2025-09-17Python 提取 TIF 中地名的完整指南 一、先明確:TIF 中的地名有哪兩種存在形式? 在開始提取前,需先判斷 TIF 文件的類型 —— ...
2025-09-17CDA 數(shù)據(jù)分析師:解鎖表結(jié)構(gòu)數(shù)據(jù)特征價值的專業(yè)核心 表結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 規(guī)范存儲的結(jié)構(gòu)化數(shù)據(jù),如數(shù)據(jù)庫表、Excel 表、 ...
2025-09-17Excel 導(dǎo)入數(shù)據(jù)含缺失值?詳解 dropna 函數(shù)的功能與實(shí)戰(zhàn)應(yīng)用 在用 Python(如 pandas 庫)處理 Excel 數(shù)據(jù)時,“缺失值” 是高頻 ...
2025-09-16深入解析卡方檢驗(yàn)與 t 檢驗(yàn):差異、適用場景與實(shí)踐應(yīng)用 在數(shù)據(jù)分析與統(tǒng)計(jì)學(xué)領(lǐng)域,假設(shè)檢驗(yàn)是驗(yàn)證研究假設(shè)、判斷數(shù)據(jù)差異是否 “ ...
2025-09-16CDA 數(shù)據(jù)分析師:掌控表格結(jié)構(gòu)數(shù)據(jù)全功能周期的專業(yè)操盤手 表格結(jié)構(gòu)數(shù)據(jù)(以 “行 - 列” 存儲的結(jié)構(gòu)化數(shù)據(jù),如 Excel 表、數(shù)據(jù) ...
2025-09-16MySQL 執(zhí)行計(jì)劃中 rows 數(shù)量的準(zhǔn)確性解析:原理、影響因素與優(yōu)化 在 MySQL SQL 調(diào)優(yōu)中,EXPLAIN執(zhí)行計(jì)劃是核心工具,而其中的row ...
2025-09-15解析 Python 中 Response 對象的 text 與 content:區(qū)別、場景與實(shí)踐指南 在 Python 進(jìn)行 HTTP 網(wǎng)絡(luò)請求開發(fā)時(如使用requests ...
2025-09-15CDA 數(shù)據(jù)分析師:激活表格結(jié)構(gòu)數(shù)據(jù)價值的核心操盤手 表格結(jié)構(gòu)數(shù)據(jù)(如 Excel 表格、數(shù)據(jù)庫表)是企業(yè)最基礎(chǔ)、最核心的數(shù)據(jù)形態(tài) ...
2025-09-15Python HTTP 請求工具對比:urllib.request 與 requests 的核心差異與選擇指南 在 Python 處理 HTTP 請求(如接口調(diào)用、數(shù)據(jù)爬取 ...
2025-09-12解決 pd.read_csv 讀取長浮點(diǎn)數(shù)據(jù)的科學(xué)計(jì)數(shù)法問題 為幫助 Python 數(shù)據(jù)從業(yè)者解決pd.read_csv讀取長浮點(diǎn)數(shù)據(jù)時的科學(xué)計(jì)數(shù)法問題 ...
2025-09-12CDA 數(shù)據(jù)分析師:業(yè)務(wù)數(shù)據(jù)分析步驟的落地者與價值優(yōu)化者 業(yè)務(wù)數(shù)據(jù)分析是企業(yè)解決日常運(yùn)營問題、提升執(zhí)行效率的核心手段,其價值 ...
2025-09-12用 SQL 驗(yàn)證業(yè)務(wù)邏輯:從規(guī)則拆解到數(shù)據(jù)把關(guān)的實(shí)戰(zhàn)指南 在業(yè)務(wù)系統(tǒng)落地過程中,“業(yè)務(wù)邏輯” 是連接 “需求設(shè)計(jì)” 與 “用戶體驗(yàn) ...
2025-09-11塔吉特百貨孕婦營銷案例:數(shù)據(jù)驅(qū)動下的精準(zhǔn)零售革命與啟示 在零售行業(yè) “流量紅利見頂” 的當(dāng)下,精準(zhǔn)營銷成為企業(yè)突圍的核心方 ...
2025-09-11CDA 數(shù)據(jù)分析師與戰(zhàn)略 / 業(yè)務(wù)數(shù)據(jù)分析:概念辨析與協(xié)同價值 在數(shù)據(jù)驅(qū)動決策的體系中,“戰(zhàn)略數(shù)據(jù)分析”“業(yè)務(wù)數(shù)據(jù)分析” 是企業(yè) ...
2025-09-11Excel 數(shù)據(jù)聚類分析:從操作實(shí)踐到業(yè)務(wù)價值挖掘 在數(shù)據(jù)分析場景中,聚類分析作為 “無監(jiān)督分組” 的核心工具,能從雜亂數(shù)據(jù)中挖 ...
2025-09-10統(tǒng)計(jì)模型的核心目的:從數(shù)據(jù)解讀到?jīng)Q策支撐的價值導(dǎo)向 統(tǒng)計(jì)模型作為數(shù)據(jù)分析的核心工具,并非簡單的 “公式堆砌”,而是圍繞特定 ...
2025-09-10