2016-09-23 82 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')。你似乎也需要指定命名空間。