【问题标题】:How to add new xml attributes to a set of xml documents?如何为一组 xml 文档添加新的 xml 属性?
【发布时间】:2019-01-29 03:16:38
【问题描述】:

我正在将目录中的一堆 xml 文档规范化为 pandas 数据框。但是,为了正确地做到这一点,我认为为每个 xml 文档分配一个 ID 会更容易,以便以后将所有文档连接到一个数据框中。因此,我尝试添加一个数字id,如下所示:

for filepath in glob(os.path.join('../data/trainingFiles/', '*.xml')):
    with open(filepath) as f:
        xml_doc = BeautifulSoup(f.read(), 'lxml')
        for i, sentences in enumerate(xml_doc.find_all("sentence")):
            sentences['pandas_id'] = str(i)
            print(sentences)

但是,上面的代码是在同一个文档中为所有句子属性添加不同的数字 id。如何为每个文档分配不同的 id(即,我想为文档中的所有元素添加相同的 id)?.. 有没有办法携带我添加 pandas id 属性的文档的引用?

【问题讨论】:

    标签: python python-3.x beautifulsoup lxml


    【解决方案1】:

    你可以试试这个代码,document_id 只会随着每个文件而改变:

    for document_id, filepath in enumerate(glob(os.path.join('../data/trainingFiles/', '*.xml'))):
        with open(filepath) as f:
            xml_doc = BeautifulSoup(f.read(), 'lxml')
            for sentences in xml_doc.find_all("sentence"):
                sentences['pandas_id'] = str(document_id)
                print(sentences)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      • 2011-03-03
      • 1970-01-01
      • 1970-01-01
      • 2011-06-03
      相关资源
      最近更新 更多