【问题标题】:Using TEI XML parser in a loop在循环中使用 TEI XML 解析器
【发布时间】:2020-11-21 15:22:07
【问题描述】:

我发现this 关于解析 TEI XML 的文章在处理单个 XML 文件时非常有用。但是,我有一个完整的目录。我通过目录的循环没有执行,我不知道为什么。

from bs4 import BeautifulSoup
import os.path
import glob

tei_docs = "../input/tei-xml-files"
    def read_tei(tei_docs):
    os.chdir(tei_docs)
for i in glob.glob(os.path.join(tei_docs, "*.xml")):
    read_file(i)

def read_file(i):

with open(i, "r") as tei:
    soup = BeautifulSoup(tei, 'lxml')

soup.title.getText()

我得到了输出

名称错误
Traceback(最近一次通话最后一次) 在

----> 1个soup.title.getText()

NameError: name 'soup' 没有定义

【问题讨论】:

    标签: python html beautifulsoup html-parsing


    【解决方案1】:

    您的代码中有几个问题,包括缩进错误。我还编写了一个脚本,用 Beautiful Soup 从 XML 文件中读取标题,如下所示:

    #!/usr/bin/env python
    # coding: utf-8
    
    from bs4 import BeautifulSoup
    import os
    from os.path import dirname, join
    directory=("C:\\Users\\mbarg\\Documents\\corpus") # location of XML files on local drive
    
    results=[] # create result list
    for infile in os.listdir(directory):
        filename=join(directory, infile)
        indata=open(filename,"r", encoding="utf-8", errors="ignore") # UTF-8 encoding errors are ignored
        contents = indata.read()
        soup = BeautifulSoup(contents,'xml')
        titles = soup.find_all('title') # get item titles
        for title in titles:
            print(title.get_text())
            results.append(title.get_text())
    print(results) # result list is shown on screen
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-30
      • 2013-03-14
      • 2014-06-18
      • 1970-01-01
      • 2018-06-12
      相关资源
      最近更新 更多