首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用python解析XML

如何使用python解析XML
EN

Stack Overflow用户
提问于 2016-09-23 19:04:55
回答 2查看 43关注 0票数 0

我想解析这个url以获得\Roman\的文本

http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=私は学生です

代码语言:javascript
复制
import urllib
import xml.etree.ElementTree as ET

url = 'http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=私は学生です'
uh = urllib.urlopen(url)
data = uh.read()
tree = ET.fromstring(data)
counts = tree.findall('.//Word')

for count in counts         
    print count.get('Roman')

但它并没有起作用。

EN

回答 2

Stack Overflow用户

发布于 2016-09-23 19:25:48

我最近遇到了一个类似的问题。这是因为我使用的是较旧版本的XML包,为了解决这个问题,我必须为xml.etree结构的每个级别创建一个循环。例如:

代码语言:javascript
复制
import urllib
import xml.etree.ElementTree as ET

url = 'http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=私は学生です'
uh = urllib.urlopen(url)
data = uh.read()
tree = ET.fromstring(data)
counts = tree.findall('.//Word')

for result in tree.findall('Result'):
    for wordlist in result.findall('WordList'):
        for word in wordlist.findall('Word'):         
            print(word.get('Roman'))

编辑:

在@omu_negru的建议下,我能够让它工作起来。还有另一个问题,在获取"Roman“的文本时,您使用的是" get”方法,该方法用于获取标记的属性。使用元素的" text“属性,可以获得开始标记和结束标记之间的文本。此外,如果没有'Roman‘标记,您将获得一个None对象,并且不能在None上获得属性。

代码语言:javascript
复制
# encoding: utf-8
import urllib
import xml.etree.ElementTree as ET

url = 'http://jlp.yahooapis.jp/FuriganaService/V1/furigana?appid=dj0zaiZpPU5TV0Zwcm1vaFpIcCZzPWNvbnN1bWVyc2VjcmV0Jng9YTk-&grade=1&sentence=私は学生です'
uh = urllib.urlopen(url)
data = uh.read()
tree = ET.fromstring(data)
ns = '{urn:yahoo:jp:jlp:FuriganaService}'
counts = tree.findall('.//%sWord' % ns)

for count in counts:
    roman = count.find('%sRoman' % ns)
    if roman is None:
        print 'Not found'
    else:
        print roman.text
票数 0
EN

Stack Overflow用户

发布于 2016-09-23 20:01:03

试试tree.findall('.//{urn:yahoo:jp:jlp:FuriganaService}Word')。似乎您还需要指定名称空间。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39659219

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档