【发布时间】:2022-01-03 01:12:54
【问题描述】:
我之前问过this question,这是一个完美的解决方案
下面是多个传统xml 文件的完美工作代码。
import pandas as pd
from glob import glob
from bs4 import BeautifulSoup
l = list()
for f in glob('*.xml'): # Changed to .txt here
pub = dict()
with open(f, 'r') as xml_file:
xml = xml_file.read()
soup = BeautifulSoup(xml, "lxml")
pub['PMID'] = soup.find('pmid').text
pub_list = soup.find('publicationtypelist')
pub['Publication_type'] = list()
for pub_type in pub_list.find_all('publicationtype'):
pub['Publication_type'].append(pub_type.text)
try:
pub['NCTID'] = soup.find('accessionnumber').text
except:
pub['NCTID'] = None
l.append(pub)
df = pd.DataFrame(l)
df = df.explode('Publication_type', ignore_index=True)
它给了我想要的输出
PMID Publication_type NCTID
0 34963793 Journal Article NCT02649218
1 34963793 Review NCT02649218
2 34535952 Journal Article None
3 34090787 Journal Article NCT02424799
4 33615122 Journal Article NCT01922037
此后我唯一改变的是 - 我提取了数据,using R and easyPubMed package。数据分批提取(每篇 100 篇文章),并以 xml 格式存储在 txt 文档中。我总共有 150 个 txt 文档。它现在只提取约 250 行,而不是约 25000 行。
当输入文件发生变化时,如何更新上面的 Python 代码并获得相同的输出?我add several txt files here 可重复性。需要提取PMID、Publication_type、NCTID。
【问题讨论】:
-
@JayPeerachai,也许你可以再次在这里提供帮助?谢谢
标签: python xml web-scraping txt pubmed