2016-09-23 77 views
0

解析XML要分析此网址,取得\罗马\文我如何通过使用Python

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

enter image description here

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') 

但没有奏效。

回答

0

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

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的建议我能得到这个工作。还有一个问题,在获取“罗马”文本时,您使用的是用于获取标签属性的“get”方法。使用元素的“text”属性,您可以在开始标签和结束标签之间获取文本。另外,如果没有'Roman'标记,您将获得一个None对象,并且无法在None上获取属性。

# 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

对不起,它仍然无效,输出为无 –

0

尝试tree.findall('.//{urn:yahoo:jp:jlp:FuriganaService}Word')。你似乎也需要指定命名空间。