ホーム 記事一覧 ブック DH週間トピックス 検索 このサイトについて
English
TEI/XMLファイルからrespStmtのnameの値を抽出する方法(GPT-4による解説)

TEI/XMLファイルからrespStmtのnameの値を抽出する方法(GPT-4による解説)

TEI/XMLファイルからrespStmtのnameの値を抽出する方法: PythonでBeautifulSoupとElementTreeを使ったアプローチ この記事では、PythonのBeautifulSoupとElementTreeを使って、TEI/XMLファイルからrespStmtのnameの値を抽出する方法を紹介します。 方法1: ElementTreeを使う まず、Pythonの標準ライブラリであるxml.etree.ElementTreeを使って、respStmtのnameの値を抽出します。 import xml.etree.ElementTree as ET # XMLファイルを読み込む tree = ET.parse('your_file.xml') root = tree.getroot() # 名前空間を定義 ns = {'tei': 'http://www.tei-c.org/ns/1.0'} # respStmtのnameの値を抽出 name = root.find('.//tei:respStmt/tei:name', ns) # nameのテキストを表示 if name is not None: print(name.text) else: print("nameタグが見つかりませんでした。") 方法2: BeautifulSoupを使う 次に、BeautifulSoupを使って、respStmtのnameの値を抽出します。まず、beautifulsoup4とlxmlライブラリがインストールされていることを確認してください。インストールされていない場合は、以下のコマンドでインストールできます。 pip install beautifulsoup4 lxml 以下のコードで、BeautifulSoupを使ってrespStmtのnameの値を抽出できます。 from bs4 import BeautifulSoup # XMLファイルを読み込む with open('your_file.xml', 'r', encoding='utf-8') as file: content = file.read() # BeautifulSoupオブジェクトを作成 soup = BeautifulSoup(content, 'lxml-xml') # respStmtのnameの値を抽出 name = soup.find('respStmt').find('name') # nameのテキストを表示 if name: print(name.text) else: print("nameタグが見つかりませんでした。") どちらの方法でも、respStmtのnameの値をPythonで簡単に抽出することができます。あなたのプロジェクトに適した方法を選んでください。