对 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/