初学py,尝试用程序整理下载的杂乱的pdf英文文献。
达成效果是:
复制pdf并重命名为:年份+杂志+文章标题格式
同时下载ris格式可以导入endnote进一步管理,生成一个csv表格
代码逻辑是:
读取pdf并提取文章中的doi号,
利用selenium控件控制Edge浏览器打开pubmed,根据doi检索文章,并提取年份、杂志和标题信息,下载ris引文至默认下载地址,
最后根据提取信息在源文件夹复制pdf文件,并重命名为特定格式。
目前存在的问题是:部分文章没有或者难以获取doi号
代码如下,欢迎交流和在此基础上修改!
以上
(我不知道为什么文章检测不通过,难以发布信息。
说我内容质量较低,于是我再补充几句废话。
还因为必须要一张图片,所以我再加一张路边拍的失焦的bug。。。)
"""
此py旨在整理pdf文献,并下载bib引文格式可以进一步导入endnote进行管理。
大概逻辑是从pdf中提取doi号,联网Pubmed搜索该文献,提取文献信息并下载bib引文,
最后在当前文件夹生成新的pdf,命名格式为:年份+期刊+标题
同时生成一个pdf_information.csv文档,用来总结已处理文献,同时储存出错形式。
注1:需要联网且有Edge浏览器,还需要安装selenium控件
注2:目前发现最大bug是,有相当一部分pdf文献中没有直接的doi号,造成无法检索,
还有少部分会提取doi号错误,导致检索失败
FranklinWhite
20220524
"""
"""
输入文件夹路径,注意路径格式,不能用“”
"""
#path = input("type your file path (Note: using "/" or "\" instead of "". ): ")
import pandas as pd
#import re
# PyMuPDF
import fitz
#Pubmed网页操作用到的包
from selenium import webdriver
import time
#用于批量修改文件名
import shutil
"""
获取指定路径下pdf名称(默认为当前文件夹),并存入pdf_file_name
"""
from pathlib import Path
filepath = Path(r"./")
#filepath = Path(path)
pdf_file_name = []
for file in filepath.rglob('*.pdf'):
pdf_file_name.append(file)
#print(file)
print("pdf_file_name: ", pdf_file_name)
pdf_info = {}
pdf_info["file_path"] = pdf_file_name
"""
提取pdf中第一个的doi号
"""
def GetDoi(pdf_name):
pdf = fitz.open(pdf_name)
pdf_doi_blocks = []
for num, p in enumerate(pdf):
content = p.get_text('blocks')
for pc in content:
#print(pc)
textblocks = list(pc[4:-2])
txt = ''.join(textblocks)
if 'doi' in txt or 'DOI' in txt:
#print("txt: ", txt)
pdf_doi_blocks.append(txt)
doi_page = pdf_doi_blocks[0]
doi_page = doi_page.replace(': ', '')
doi_page = doi_page.replace(':', '')
pdf_doi = []
pdf_doi_split = doi_page.split()
#print(pdf_doi_split)
for x in range(len(pdf_doi_split)):
if pdf_doi_split[x].find('doi.org/') != -1:
s = pdf_doi_split[x]
n = s.find('doi.org/')
d = s[n+8:]
pdf_doi.append(d)
elif pdf_doi_split[x].find('DOI') != -1:
s = pdf_doi_split[x]
a = len(s) - s.find('DOI')
if a <= 5:
m = pdf_doi_split[x+1].replace('n', '')
pdf_doi.append(m)
else:
m = pdf_doi_split[x]
n = m.find('DOI')
d = s[n+3:]
pdf_doi.append(d)
elif pdf_doi_split[x].find('doi') != -1:
s = pdf_doi_split[x]
a = len(s) - s.find('doi')
if a <= 5:
m = pdf_doi_split[x+1]
pdf_doi.append(m)
else:
m = pdf_doi_split[x]
n = m.find('doi')
d = s[n+3:]
pdf_doi.append(d)
if len(pdf_doi) == 0:
t = pdf.metadata['title']
pdf_doi.append(t)
return pdf_doi[0]
"""
将pdf_file_name中的doi依次提取并储存至pdf_doi
"""
pdf_doi = []
for path in pdf_file_name:
#print(path)
#print(GetDoi(path))
try:
pdf_doi.append(GetDoi(path))
except:
pdf_doi.append("doi_error")
print("doi not found")
#print (pdf_doi)
pdf_info["file_doi"] = pdf_doi
"""
从Pubmed上提取文章信息
"""
def Pubmed_Exract(doi):
citation_info = {}
#打开pubmed网页
url = 'https://pubmed.ncbi.nlm.nih.gov/?term='+doi+'&size=20&page=1'
driver = webdriver.Edge()
driver.get(url)
driver.implicitly_wait(5)
#提取文章标题
citation_info["Title"] = driver.find_element_by_class_name('heading-title').text
#提取文章发表日期
d = driver.find_element_by_xpath('/html/head/meta[47]')
date = d.get_attribute('content')
citation_info["Date"] = date
a = date.split(" ")
if len(a) == 1:
y = a[0][-4:]
else:
for n in a:
if len(n) == 4:
y = n
citation_info["Year"] = y
#提取杂志名
j = driver.find_element_by_xpath('/html/head/meta[49]')
citation_info["Journal"] = j.get_attribute('content')
#下载引文至默认地址,本机为c:\download
driver.find_element_by_class_name('more-actions-trigger').click()
driver.find_element_by_xpath('//*[@id="more-actions-dropdown"]/div/ul/li[4]/a').click()
time.sleep(2)
driver.find_element_by_xpath('//*[@id="citation-manager-action-panel-form"]/div/button[1]').click()
time.sleep(2)
#退出网页
driver.quit()
print(citation_info)
return citation_info
pdf_title = []
pdf_date = []
pdf_year = []
pdf_jour = []
for doi in pdf_doi:
if doi == "doi_error":
print("skipping PubMed due to doi error")
pdf_title.append("pubMed_error")
pdf_date.append("pubMed_error")
pdf_year.append("pubMed_error")
pdf_jour.append("pubMed_error")
pass
else:
try:
pubmed_info = Pubmed_Exract(doi)
pdf_title.append(pubmed_info["Title"])
pdf_date.append(pubmed_info["Date"])
pdf_year.append(pubmed_info["Year"])
pdf_jour.append(pubmed_info["Journal"])
except:
pdf_title.append("pubMed_error")
pdf_date.append("pubMed_error")
pdf_year.append("pubMed_error")
pdf_jour.append("pubMed_error")
print("PubMed Error")
#print("Title: ", pdf_title)
#print("Date: ", pdf_date)
#print("Year: ", pdf_year)
#print("Journal: ", pdf_jour)
pdf_info["title"] = pdf_title
pdf_info["date"] = pdf_date
pdf_info["year"] = pdf_year
pdf_info["Journal"] = pdf_jour
"""
将信息存入py程序目录下一个csv文件
"""
pdf_information = pd.DataFrame(pdf_info)
print(pdf_information)
pdf_information.to_csv("./pdf_information.csv", index = False)
"""
pdf批量重命名:'year' + 'Journal' + 'title' + '.pdf'
"""
for i in range(len(pdf_info["file_path"])):
if pdf_info["year"][i] == "pubMed_error":
print("skipping renaming due to PubMed error")
pass
else:
new_name = pdf_info["year"][i] + "_" + pdf_info["Journal"][i] + "_" + pdf_info["title"][i] + ".pdf"
new_name = new_name.replace(':', '_')
new_name = new_name.replace('?', '')
src = str(pdf_info["file_path"][i])
ori_name_s = src.split('\')
ori_name_s[-1] = new_name
dst = '\'.join(ori_name_s)
shutil.copy(src, dst)
print("Program finished!")



