用python加密程序使用特定函数

2024-05-19 03:02:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试编写一个python程序,它将使用用户给出的等式来加密用户的输入消息。这将是我的第一个程序(除了“helloworld”和“number guesser”)。我尽量说得更具体些。我认为首先要做的是,创建一个列表,写下所有的字母和它们对应的数字。要求输入字符串,并要求用户编写一个类似3x+2的公式。我要做的是,对于字符串输入的每个字母,从列表中找到相应的数字,并使用公式生成另一个输出。我想我应该拆分要加密的消息并找到每个数字的值,但是我该如何让python将这些数字放入等式中呢?谢谢你的帮助


Tags: 字符串用户程序消息number列表字母数字
1条回答
网友
1楼 · 发布于 2024-05-19 03:02:16

您可以在for循环中逐个字符,并使用ord()获取ascii字符的序号。要计算算术表达式,可以使用ast(参见Evaluating a mathematical expression in a string)。在此之前,您需要将“x”替换为之前收集的序数。你知道吗

这里有一个很小的例子,希望能做到这一点。你知道吗

用法:

$ python mycrypt.py "Stack Overflow is Awesome!" "3x+2"
:251:350:293:299:323:98:239:356:305:344:308:326:335:359:98:317:347:98:197:359:305:347:335:329:305:101:

代码:

#!/usr/bin/python
import sys
import ast
import operator as op

# supported operators
operators = {ast.Add: op.add, ast.Sub: op.sub, ast.Mult: op.mul,
             ast.Div: op.truediv, ast.Pow: op.pow, ast.BitXor: op.xor,
             ast.USub: op.neg}

def eval_expr(expr):
    """
    >>> eval_expr('2^6')
    4
    >>> eval_expr('2**6')
    64
    >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)')
    -5.0
    """
    return eval_(ast.parse(expr, mode='eval').body)

def eval_(node):
    if isinstance(node, ast.Num): # <number>
        return node.n
    elif isinstance(node, ast.BinOp): # <left> <operator> <right>
        return operators[type(node.op)](eval_(node.left), eval_(node.right))
    elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
        return operators[type(node.op)](eval_(node.operand))
    else:
        raise TypeError(node)

# Your first argument (e.g. "Stack Overflow is Awesome!")
text = sys.argv[1]
# Your second argument (e.g. "3x+2")
calc = sys.argv[2]

# Print beginning
sys.stdout.write(":")   
# For each character in text do your calculation                
for c in text:
    # Generate expression by replacing x  with ascii ordinal number 
    #  prefixed with a multiplicator. 
    # -> character "a" has ordinal number "97"
    # -> expression "3x+2" will be changed to "3*97+2"
    #  likewise the expression "3*x+2" will be changed to "3**97+2" 
    #  which might not be the expected result.
    expr = calc.replace("x", "*" + str(ord(c))) 
    # Evaluate expression
    out = eval_expr(expr)
    # Print cipher with trailing colon and without newline                          
    sys.stdout.write(str(out) + ":")
# Print ending newline
print("")                                           

相关问题 更多 >

    热门问题