[英]how do i use a line from a text file as a function input in python?
我写了一个函数,允许您通过python shell控制turtle模块,这是其中的一部分:
import turtle
turtle.showturtle()
def turtle_commands():
instructions = input().split()
i = instructions[0]
if len(instructions) == 2:
if i == 'forward' :
n = int(instructions[1])
turtle.forward(n)
例如当您输入
forward 100
乌龟向前移动100像素。 我对大多数乌龟命令都做过同样的事情-向后,向左,向右,放大,缩小,颜色等等。
我的问题是,有什么方法可以从文本文件加载这些命令吗? 我在想这样的事情
instructions = input().split()
i = instructions[0]
if i == 'load' :
n = str(instructions[1])
l = open(n, 'r')
while True:
line = l.readline()
turtle_commands(line) #i don't really know what i did here, but hopefully you get the point
if not line:
break
该程序必须接受来自文件和外壳程序的命令。 谢谢您的回答。
假设所有命令的格式为<command> <pixels>
:
# Create a dictionary of possible commands, with the values being pointers
# to the actual function - so that we can call the commands like so:
# commands[command](argument)
commands = {
'forward': turtle.forward,
'backwards': turtle.backward,
'left': turtle.left,
'right': turtle.right
# etc., etc.
}
# Use the `with` statement for some snazzy, automatic
# file setting-up and tearing-down
with open('instructions_file', 'r') as instructions:
for instruction in instructions: # for line in intructions_file
# split the line into command, pixels
instruction, pixels = instruction.split()
# If the parsed instruction is in `commands`, then run it.
if instruction in commands:
commands[instruction](pixels)
else:
# If it's not, then raise an error.
raise()
应该非常简单-只需更改您的turtle_commands()
函数即可从参数而不是input()
函数获取其输入,如下所示:
def turtle_commands(command):
instructions = command.split()
i = instructions[0]
if len(instructions) == 2:
if i == 'forward' :
n = int(instructions[1])
turtle.forward(n)
然后,使用从文件中读取的输入命令来调用函数,就像在您建议的代码中用turtle_commands(line)
行turtle_commands(line)
。
在itertools
下使用map()
就足够了。 l.readlines()
将以列表形式返回文件中的所有行,而map
内置函数将遍历列表中的所有元素,并将其作为参数提供给函数turtle_commands
map(turtle_commands, [ int(_) for _ in l.readlines() ] )
map()
将向函数提供参数列表。
map(function, params_list)
>>> map(lambda x: x + 1, [1, 2, 3, 4, 5, 6])
[2, 3, 4, 5, 6, 7]
有一个非常简单的解决方案-使用geattr函数。 如果您有一系列空格/行尾命令:
instructions = data.split()
commands = instructions[::2]
params = instructions[1::2]
for command, param in zip(commands,params):
try:
getattr(turtle, command)(int(param))
except AttributeError:
print('Bad command name:{}'.format(command))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.