python - 根据输入的参数数量重复输出

标签 python

对 Python 非常陌生,我的知识范围是我在过去几个小时内刚刚构建的:

from sys import argv
import requests
import xml.etree.ElementTree as ET

script, gameid = argv

game = requests.get("http://boardgamegeek.com/xmlapi/game/" + (gameid))
r = game.text
root = ET.fromstring(r)
boardgame = root.findall('boardgame')
for b in boardgame:
    name = b.find('name').text
    year = b.find('yearpublished').text
    mech = b.find('boardgamemechanic').text
    cat = b.find('boardgamecategory').text
    print (name,",",year,",",mech,",",cat)

这正在做我想要的事情,即根据用户输入为我提供上述四条信息。

我想知道的是是否可以运行此脚本 n 次,其中 n 是在 cmd 行输入的参数数量?

输出如下所示:

C:\Python>bgg.py 822
Carcassonne , 2000 , Area Control / Area Influence , City Building

C:\Python>bgg.py 25417
BattleLore , 2006 , Campaign / Battle Card Driven , Fantasy

我想要的是如果我能得到类似下面的东西:

C:\Python>bgg.py 822 25417
Carcassonne , 2000 , Area Control / Area Influence , City Building
BattleLore , 2006 , Campaign / Battle Card Driven , Fantasy

干杯

最佳答案

关键目标是重复需要多次执行操作的代码。为此,从 argv 的列表中提取您的游戏 ID(您似乎已经知道这是如何工作的)。现在,迭代每个 ID 并为每个 ID 执行与在原始代码中对 ID 执行的操作相同的操作。

from sys import argv
import requests
import xml.etree.ElementTree as ET

gameids = argv[1:]

for gameid in gameids: 
    game = requests.get("http://boardgamegeek.com/xmlapi/game/" + (gameid))
    r = game.text
    root = ET.fromstring(r)
    boardgame = root.findall('boardgame')
    for b in boardgame:
        name = b.find('name').text
        year = b.find('yearpublished').text
        mech = b.find('boardgamemechanic').text
        cat = b.find('boardgamecategory').text

        print (name, ",", year, ",", mech, ",", cat)

现在,使用 python bgg.py 822 25417 调用您的程序,您将看到您正在寻找的结果。

关于python - 根据输入的参数数量重复输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44876236/

相关文章:

python - 向 Pyramid 下的 jinja2 添加自定义过滤器

python - 如何获取 Spark DataFrame 中每行列表中最高值的索引? [PySpark]

python - 等价于 Python 中的 LinkedHashMap

python - 如何诊断消失的端口监听器?

python - TensorFlow 读取并解码 BATCH 图像

python - 为什么信号处理程序中的打印操作可能会改变死锁情况?

python - PyQt4:信号槽机制无法正常工作 'List of buttons'

python - 在django中确定属性是否为 `DeferredAttribute`

python - Pandas 数据帧 : how to get column mean valuebut taking into account only the rows that have lower index than the one I want to get the mean

python - celery 进程 'Worker' 以 'exitcode 1' 退出