【问题标题】:Python Xml Parsing for Wolfram ApiWolfram Api 的 Python Xml 解析
【发布时间】:2014-09-02 19:01:01
【问题描述】:

我正在尝试使用 python xml 解析脚本输出 wolfram api。这是我的脚本:

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)

我知道它只是获取代码标题部分中所有内容的属性,但这是一个开始。

这是输出的 sn-p:

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

我试图让它只打印出标签中的内容。有谁知道如何编辑代码来获得它?

【问题讨论】:

  • 所以你想打印sqrt(2)

标签: python xml parsing wolframalpha


【解决方案1】:

只有&lt;plaintext&gt; 元素包含文本:

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

.text 属性保存元素的文本。

对于您的 URL,将打印:

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

看起来&lt;pod&gt; 标签也有有趣的标题:

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

【讨论】:

  • 这正是我想要的。谢谢!
【解决方案2】:

更多示例:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-16
    • 1970-01-01
    • 2021-06-29
    相关资源
    最近更新 更多