解析整个目录Etree Parse lxm

2024-04-28 20:08:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要在目录中用xml标记解析txt文件(我已经用glob创建了一个语料库),但是etreeparse一次只允许一个文件。如何设置一个循环来同时解析所有文件?目标是使用请求将这些文件添加到Elasticsearch中。到目前为止,我得到的是:

import json
import os
import re
from lxml import etree
import xmltodict 
import glob

corpus=glob.glob('path/*.txt')
ns=dict(tei="http://www.tei-c.org/ns/1.0")
tree = etree.ElementTree(file='path/file.txt')
doc = {
    "author": tree.xpath('//tei:author/text()', namespaces=ns)[0],
    "title": tree.xpath('//tei:title/text()', namespaces=ns)[0],
    "content": "".join(tree.xpath('//tei:text/text()', namespaces=ns))
    }

Tags: 文件pathtextimporttxttreetitletei
1条回答
网友
1楼 · 发布于 2024-04-28 20:08:22

只需迭代corpus列表。但是,您将希望使用一个容器(如列表或字典)来保存单独解析的数据。下面假设.txt文件是格式良好的.xml文件,并保持相同的结构,包括tei命名空间:

import os, glob
from lxml import etree

corpus = glob.glob('path/*.txt')
ns = dict(tei="http://www.tei-c.org/ns/1.0")

xmlList = []; xmlDict = {}

for file in corpus:
    tree = etree.parse(file)
    doc = {
           "author": tree.xpath('//tei:author/text()', namespaces=ns)[0],
           "title": tree.xpath('//tei:title/text()', namespaces=ns)[0],
           "content": "".join(tree.xpath('//tei:text/text()', namespaces=ns))
          }
    # LIST OF DOC DICTS
    xmlList.append(doc)                

    # DICTIONARY OF DOC DICTS, KEY IS FILE NAME
    key = os.path.basename(file).replace('.txt', '')
    xmlDict[key] = doc     

相关问题 更多 >