简体   繁体   English

我如何使用文本文件中的一行作为python中的函数输入?

[英]how do i use a line from a text file as a function input in python?

I have written a function which allows you to control turtle module through python shell, here's a part of it: 我写了一个函数,允许您通过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)

for example when you type in 例如当您输入

forward 100

the turtle moves forward 100 pixels. 乌龟向前移动100像素。 I've done the same thing with most turtle commands- backwards, left, right, penup, pendown, color and so on. 我对大多数乌龟命令都做过同样的事情-向后,向左,向右,放大,缩小,颜色等等。

My question is, is there any way to load these commands from a text file? 我的问题是,有什么方法可以从文本文件加载这些命令吗? i was thinking of something like that 我在想这样的事情

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

The program must accept commands from both file and shell. 该程序必须接受来自文件和外壳程序的命令。 Thank you for your answers. 谢谢您的回答。

Assuming all commands are in the format <command> <pixels> : 假设所有命令的格式为<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()

Should be pretty simple -- just change your turtle_commands() function to get its input from an argument rather than the input() function, like this: 应该非常简单-只需更改您的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)

Then, call your function with the input commands you read from your file, just as you've done in your proposed code with the line turtle_commands(line) . 然后,使用从文件中读取的输入命令来调用函数,就像在您建议的代码中用turtle_commands(line)turtle_commands(line)

Using map() under itertools will be enough. itertools下使用map()就足够了。 l.readlines() will return all lines in the file as a list, and map builtin function will iterate through all elements in the list and supply them as arguments to the function turtle_commands l.readlines()将以列表形式返回文件中的所有行,而map内置函数将遍历列表中的所有元素,并将其作为参数提供给函数turtle_commands

map(turtle_commands, [ int(_) for _ in l.readlines() ] )

map() will supply a list of parameters to the function. map()将向函数提供参数列表。

map(function, params_list)

>>> map(lambda x: x + 1, [1, 2, 3, 4, 5, 6])
[2, 3, 4, 5, 6, 7]

There is a very simple solution - use geattr function. 有一个非常简单的解决方案-使用geattr函数。 If you have a sequence of space/end-of-line commands: 如果您有一系列空格/行尾命令:

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.

相关问题 如何从文本中提取一行用作python函数的输入 - how to take a line from a text to use as input for a function python 如何从文件中读取特定行的文本并将其用作函数的参数 - How do i read a specific line of text from a file and use it as a parameter for a function 如何从python的输入文件中选择特定行 - How do I choose a specific line from a input file in python 如何从python中的文本文件中切出一行? - How do I slice a line from a text file in python? 如何从 python 中的文本文件中删除特定行 - How do I remove a specific line from a text file in python 如何将文本文件中的输入格式化为 python 中的 defaultdict - How do I format input from a text file into a defaultdict in python 如何从文本文件中获取每一行并将其拆分,以便我可以在 python 中单独使用它们 - How do I get each line from a text file and split it so that I can use them all separately in python 如何从 python 中的文本文件中获取 function 参数? - How do I fetch function parameters from a text file in python? 如何修改 python 脚本以使用外部文件作为命令行中的输入? - How do I modify a python script to use an external file as the input in the command line? 如何将多行文本文件分解为可以迭代的列表,以检查 python 中的输入 == 文本文件? - How do I break a multiple line text file, into a list which can be iterated through to check if input == text file in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM