Python gzip圧縮されたxmlファイルを扱う
引き続きPubChemからダウンロードした化合物リストを扱います。
サンプルとしてここら辺から適当な.xml.gzファイルをダウンロードしてみてください。
gzipからテキストを取得してxmlとして読み込む
こんな感じで化合物のSIDと名前(リスト)を取得しました。
import os
import gzip
import xml.etree.ElementTree as ET
# gzipファイルからテキストを取得
def read_gz(file_path):
print('read_gz: ' + file_path)
file_name, ext = os.path.splitext(file_path)
if not ext == '.gz':
print('this file is not .gz')
return
with gzip.open(file_path, 'rt', 'utf_8') as f:
content = f.read()
return content
# テキストからxmlを作成
def read_xml(content):
print('read_xml: ')
root = ET.fromstring(content)
elms = root.findall('{http://www.ncbi.nlm.nih.gov}PC-Substance')
substances = []
for elm in elms:
sid = elm.find('{http://www.ncbi.nlm.nih.gov}PC-Substance_sid').find('{http://www.ncbi.nlm.nih.gov}PC-ID').find('{http://www.ncbi.nlm.nih.gov}PC-ID_id').text
names_elm = elm.find('{http://www.ncbi.nlm.nih.gov}PC-Substance_synonyms').findall('{http://www.ncbi.nlm.nih.gov}PC-Substance_synonyms_E')
names = [elm.text for elm in names_elm]
substances.append({
'sid': sid,
'names': names
})
return substances