如何使用Beautiful Soup解析此XML文件?

0 投票
1 回答
4907 浏览
提问于 2025-04-28 17:53

我正在尝试使用Beautiful Soup来解析xml文件,我看过Crummy网站上的文档,但没有找到关于xml解析的满意内容。目前,我只弄明白了这些:

file = open("input.xml")
page = file.read()

soup = BeautifulSoup(page, "xml")
for word in soup.findAll('word'):
    word_attr = dict(word.attrs)
    netag = word.find('ner')
    nertag = dict(netag)
    print ("STOP", nertag['ner'])

但是,这并没有起作用。我的xml文件格式是:

<?xml version="1.0" encoding="utf-8"?>
<root>
 <document>
  <sentences>
   <sentence id="1">
    <tokens>
     <token id="1">
      <word>
       Starbucks
      </word>
      <lemma>
       Starbucks
      </lemma>
      <CharacterOffsetBegin>
       0
      </CharacterOffsetBegin>
      <CharacterOffsetEnd>
       9
      </CharacterOffsetEnd>
      <POS>
       NNP
      </POS>
      <NER>
       ORGANIZATION
      </NER>
     </token>
     <token id="2">
      <word>
       to
      </word>
      <lemma>
       to
      </lemma>
      <CharacterOffsetBegin>
       10
      </CharacterOffsetBegin>
      <CharacterOffsetEnd>
       12
      </CharacterOffsetEnd>
      <POS>
       TO
      </POS>
      <NER>
       O
      </NER>
     </token>
<token id="5">
  <word>
   .
  </word>
  <lemma>
   .
  </lemma>
  <CharacterOffsetBegin>
   263
  </CharacterOffsetBegin>
  <CharacterOffsetEnd>
   264
  </CharacterOffsetEnd>
  <POS>
   .
  </POS>
  <NER>
   O
  </NER>
 </token>
 </tokens>
   </sentence>
  </sentences>
 </document>
</root>

我想做的是提取NER值,把句子中的句号用“STOP”替换掉,然后把结果写入另一个txt文件。

比如对于一个句子:Starbucks in New York is good.(写在xml里)应该得到:ORGANIZATION in LOCATION is good STOP

有没有人能帮我一下,告诉我怎么做?或者给我一些关于Beautiful Soup解析xml的足够文档?

暂无标签

1 个回答

1

你需要找一个兄弟标签;无论是下一个兄弟还是上一个兄弟都可以,这样的话,先去找父标签会更简单:

for word in soup.find_all('word'):
    ner = word.parent.find('NER')
    if not ner: continue
    print '{} in {} is good'.format(ner.string.strip(), word.string.strip())

示例:

>>> for word in soup.find_all('word'):
...     ner = word.parent.find('NER')
...     if not ner: continue
...     print '{} in {} is good'.format(ner.string.strip(), word.string.strip())
... 
ORGANIZATION in Starbucks is good
O in to is good
O in . is good

不过,你也可以直接使用 xml.etree.ElementTree API 来完成这个任务;它处理 XML 的能力和 BeautifulSoup 一样强。既然你已经安装了 lxml,你可以使用它们的 ElementTree 实现。

撰写回答