
來源:早起Python
作者:陳熹
大家好,我是早起。
在之前的文章 批量翻譯文檔 中,我們介紹了如何調(diào)用百度翻譯API完成實際的文檔翻譯需求。如果是科研、深度學習等需要經(jīng)常閱讀大量論文的工作,批量翻譯就能大大提高效率。
本文將進一步使用 Python 實現(xiàn)另一個在科研學術領域的辦公自動化應用?!?/span>結(jié)合爬蟲批量翻譯文獻題目和摘要,并存儲搜索和翻譯結(jié)果至 Excel中」
完成效果如下,指定的外文文獻標題、摘要都被批量翻譯后存儲在Excel中,我們可以大致瀏覽后有選擇性的挑選文章閱讀!
本文以ACM協(xié)會的文獻為例,搜索的關鍵詞是 “對抗生成網(wǎng)絡+眼底” ,即 “GAN+fundus”
本文需求可以看做三塊內(nèi)容:爬蟲+翻譯+存儲 在使用百度的通用翻譯 API 之前需要完成以下工作:
“使用百度賬號登錄百度翻譯開放平臺(
http://api.fanyi.baidu.com)注冊成為開發(fā)者,獲得APPID;進行開發(fā)者認證(如僅需標準版可跳過);開通通用翻譯API服務:開通鏈接參考技術文檔和Demo編寫代碼”
完成后在個人頁面在即可看到 ID 和密鑰,這個很重要!
關于如何使用Python爬取翻譯結(jié)果的細節(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 捕獲錯誤避免中途因為提交的文本為空,而導致的報錯終止程序
存儲部分,通過 openpyxl 或者 xlwings 存儲到 Excel 中就可以
爬蟲部分,兩個網(wǎng)站的邏輯非常類似,具體見下文
首先爬取ACM的摘要,在首頁搜索框中輸入:GAN+fundus 跳轉(zhuǎn)后可以發(fā)現(xiàn),URL包含了關鍵詞:
那么后面的搜索就可以直接用URL拼接:
keyword = 'GAN+fundus' url_init = r'https://dl.acm.org/action/doSearch?AllField=' url =url_init + keyword
搜索結(jié)果非常多,本文爬取第一頁文章的摘要為例,后續(xù)讀者當關鍵詞鎖定的文獻比較少或者想獲取全部文獻,可以自行尋找URL翻頁邏輯
同時我們發(fā)現(xiàn),摘要顯示不全,確認源代碼和ajax動態(tài)加載不包含完整摘要,因此可以考慮進入各文獻的詳情頁獲取摘要:
回到搜索結(jié)果頁,對詳情頁分析可以發(fā)現(xiàn)每個文獻可獲取的href跟 dl.acm.org 拼接后即為詳情頁URL:
接下來就可以利用Xpath獲取搜索頁第一頁全部文獻的 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ù),輸出返回值就是中文翻譯形式了。注意免費的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 標記文章的順序,并在每篇文章解析和翻譯完后利用 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'文獻輸出.xlsx')
最終實現(xiàn)效果如下,可以看到指定的文章標題、摘要都被翻譯提取出來,我們可以大致瀏覽后有選擇的查閱文章。
另外還有一個重要的計算機協(xié)會,IEEE(https://ieeexplore.ieee.org/Xplore/home.jsp),網(wǎng)頁信息爬取邏輯和ACM非常類似,不再贅述
綜合各種辦公自動化技術,我們可以實現(xiàn)各式各樣的辦公或科研需求,扎實的技術是最重要的前提。
例如本文的需求,其實我們還可以通過 openpyxl 或者 xlwings 存儲到 Excel 中,實際上還可以 python-docx 寫入 Word 中,甚至從文獻中獲取圖片,借助 python-pptx 寫入 PPT 中。
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關鍵? 在循環(huán)神經(jīng)網(wǎng)絡(RNN)家族中,長短期記憶網(wǎng)絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務的價值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數(shù)據(jù)查詢到趨勢預判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領域中,準確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內(nèi)權威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網(wǎng)絡(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調(diào)研數(shù)據(jù)中的深度應用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03