2013-03-15 56 views
0

我想使用python xml解析腳本獲取wolfram api的輸出。這是我的腳本:Wolfram Api的Python Xml解析

import urllib 
import urllib.request 
import xml.etree.ElementTree as ET 

xml_data=urllib.request.urlopen("http://api.wolframalpha.com/v2/query?input=sqrt+2&appid=APLTT9-9WG78GYE65").read() 
root = ET.fromstring(xml_data) 

for child in root: 
    print (child.get("title")) 
    print (child.attrib) 

我知道它只獲取代碼標題部分的所有內容的屬性,但它是一個開始。

下面是輸出的一個片段:

<pod title="Input" scanner="Identity" id="Input" position="100" error="false" numsubpods="1"> 
<subpod title=""> 
<plaintext>sqrt(2)</plaintext> 

我試圖讓它只打印出什麼是在標籤。有誰知道如何編輯代碼來獲取?

+0

所以你想要'sqrt(2)'打印? – 2013-03-15 21:13:43

回答

2

只有<plaintext>元素包含文本:

for pt in root.findall('.//plaintext'): 
    if pt.text: 
     print(pt.text) 

.text屬性モ元素的文本。

對於您的網址,即打印:

sqrt(2) 
1.4142135623730950488016887242096980785696718753769480... 
[1; 2^_] 
Pythagoras's constant 
sqrt(2)~~1.4142 (real, principal root) 
-sqrt(2)~~-1.4142 (real root) 

它看起來像<pod>標籤有有趣的標題太:

for pod in root.findall('.//pod'): 
    print(pod.attrib['title']) 
    for pt in pod.findall('.//plaintext'): 
     if pt.text: 
      print('-', pt.text) 

然後打印:

Input 
- sqrt(2) 
Decimal approximation 
- 1.4142135623730950488016887242096980785696718753769480... 
Number line 
Continued fraction 
- [1; 2^_] 
Constant name 
- Pythagoras's constant 
All 2nd roots of 2 
- sqrt(2)~~1.4142 (real, principal root) 
- -sqrt(2)~~-1.4142 (real root) 
Plot of all roots in the complex plane 
+0

這正是我想要的。謝謝! – user1985351 2013-03-15 21:19:54

0

一些例子:

import httplib2 
import xml.etree.ElementTree as ET 


def request(query): 
    query = urllib.urlencode({'input':query}) 
    app_id = "Q6254U-URKKHH9JLL" 
    wolfram_api = "http://api.wolframalpha.com/v2/query?appid="+app_id+"&format=plaintext&podtitle=Result&"+query 
    resp, content = httplib2.Http().request(wolfram_api) 
    return content 

def response(query): 
    content = request(query)  
    root = ET.fromstring(content) 
    error = root.get('error') 
    success = root.get('success') 
    numpods = root.get('numpods') 
    answer= '' 
    if success and int(numpods) > 0 : 
     for plaintext in root.iter('plaintext'): 
      if isinstance(plaintext.text, str) : 
       answer = answer + plaintext.text 
     return answer 
    elif error: 
     return "sorry I don't know that" 
request("How old is the queen")