gpt4 book ai didi

python - 获取函数作为字符串然后运行它

转载 作者:太空宇宙 更新时间:2023-11-04 00:55:21 24 4
gpt4 key购买 nike

我有这样的脚本:

from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = lowercase + uppercase + digits + punctuation

for n in range(1, 2+1):
for comb in product(chars, repeat=n):
print ''.join(comb)

它工作正常。想象一下 chars 是由外部用户提供的:

import sys
from string import digits, uppercase, lowercase, punctuation
from itertools import product

chars = sys.argv[1] # sys.argv[1] is 'lowercase+uppercase+digits+punctuation'

for n in range(1, 2+1):
for comb in product(chars, repeat=n):
print ''.join(comb)

当运行 script.py 时:当你说时它没有结果:

chars = lowercase + uppercase + digits + punctuation

现在如何获取之前的结果呢?

最佳答案

您可以使用字典将用户输入映射到相应的字符串。

>>> input_to_chars = {
... 'lowercase': lowercase,
... 'uppercase': uppercase,
... 'digits': digits,
... 'punctuation': punctuation
... }

从用户输入构造字符,如下所示:

>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(input_to_chars[i] for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

或者根据@schwobaseggl 在评论中的提示:

>>> import string
>>> inp = raw_input('what character sets do you want? ')
what character sets do you want? lowercase+uppercase+digits+punctuation
>>> chars = ''.join(getattr(string, i) for i in inp.split('+'))
>>> chars
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

字典解决方案很容易扩展,如果您不想扩展您的程序以接受不是string 属性的用户输入,getattr 解决方案很好.

关于python - 获取函数作为字符串然后运行它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35391900/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com