【问题标题】:xml with BeautifulSoup带有 BeautifulSoup 的 xml
【发布时间】:2017-05-08 07:59:08
【问题描述】:
from bs4 import BeautifulSoup

list = (glob.glob("/home/anastasiya/PycharmProjects/bachelor/rutexts/*.xhtml"))
for text in list:
print(text)
with open(text, "r", encoding="windows-1251") as file:
    with open("ruscorpus.txt", "a") as file2: 
        for line in file:
            soup = BeautifulSoup(line, "lxml")
            if soup.w is not None:
                        file2.write("{wort}\t{gr}\t{lex}\n".format(
                        lex=soup.w.ana.get('lex'),
                        gr=test(soup.w.ana.get('gr')),
                        wort=soup.w.contents[-1]))

我尝试从 xml 中获取一些信息。格式是这样的。 该程序运行,但如果我们在一个 w 标签中有 2 个单词,它将第一个作为带有整个标签的输出:

【问题讨论】:

  • 为什么要明智地阅读 xml 数据线?

标签: python xml beautifulsoup


【解决方案1】:

Check online demo

使用soup.find_all('w')会给出所有w的列表

soup.w 只给出w 的第一次出现

【讨论】:

    【解决方案2】:

    1,您的代码正在尝试逐行读取文件text,然后将其传递给bs4进行解析。我建议你可以直接将打开的文件引用传递给bs4。

    2、在bs4中,你可以通过find_all找到w等所有特定标签的内容。

    像这样更改您的代码:

    with open(text, "r", encoding="windows-1251") as file1, open("ruscorpus.txt", "a") as file2: 
        xml_soup = BeautifulSoup(file1,'lxml')
        for w in xml_soup.find_all('w'): # get all w tag and parse them
            file2.write("{wort}\t{gr}\t{lex}\n".format(lex=w.ana.get('lex'),gr=w.ana.get('gr'),wort=w.contents[-1]))
    

    【讨论】:

    • 谢谢,你知道吗,我怎样才能得到标点符号,那是 w 之外的? Закрой </w> - <w> <ana lex="закрыть" gr="V,pf,tran=sg,act,2p,imper" joined="hyphen"/> закрой .
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2016-07-09
    • 1970-01-01
    相关资源
    最近更新 更多