how to search a word in xml file and print it in python

纵饮孤独 提交于 2020-01-05 11:07:30

问题


i want to search a specific word(which is entered by user) in .xml file. This is my xml file.

<?xml version="1.0" encoding="UTF-8"?>
<words>
<entry>
<word>John</word>
<pron>()</pron>
<gram>[Noun]</gram>
<poem></poem>
<meanings>
<meaning>name</meaning>
</meanings>
</entry>
</words>

here is my Code

import nltk
from nltk.tokenize import word_tokenize
import os
import xml.etree.ElementTree as etree


sen = input("Enter Your sentence - ")

print(sen)
print("\n")
print(word_tokenize(sen)[0])

tree = etree.parse('roman.xml')
node=etree.fromstring(tree)

#node=etree.fromstring('<a><word>waya</word><gram>[Noun]</gram> 
<meaning>talking</meaning></a>')
s = node.findtext(word_tokenize(sen)[0])
print(s)

i have tried everything but still its giving me error

a bytes-like object is required, not 'ElementTree'

i really don't know how to solve it.


回答1:


the error happens because you are passing an elementtree object to the fromstring () methods. Do like this:

>>> import os
>>> import xml.etree.ElementTree as etree
>>> a = etree.parse('a.xml')
>>> a
<xml.etree.ElementTree.ElementTree object at 0x10fcabeb8>
>>> b = a.getroot()
>>> b
<Element 'words' at 0x10fb21f48>
>>> b[0][0].text
'John'

Use find() and findall() methods to search.

for more info, check lib: https://docs.python.org/3/library/xml.etree.elementtree.html

Simple example:

test.xml

<?xml version="1.0" encoding="UTF-8"?>
<words>
  <word value="John"></word>
  <word value="Mike"></word>
  <word value="Scott"></word>
</words>

example.py

root = ET.parse("test.xml")
>>> search = root.findall(".//word/.[@value='John']")
>>> search
[<Element 'word' at 0x10be9c868>]
>>> search[0].attrib
{'value': 'John'}
>>> search[0].tag
'word'


来源:https://stackoverflow.com/questions/52908989/how-to-search-a-word-in-xml-file-and-print-it-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!