我如何更改函数名,以便让Python读起来像是,哈哈是Elif,Hihi是其他. 现在的代码类似于:

if x == 7 or x == 2:
    print(":)")
elif x == 3:
    print(":(")
else:
    print(":|")

我希望我的代码是这样的:

hehe x == 7 or x == 2:
    print(":)")

haha x == 3:
    print(":(")
hihi:
    print(":|")

我想更改每个函数的名称,使代码完全不可读.这没有实际用处,我想把它做出来只是为了好玩. 我试着做一个编译器,我得到了一些类似于Basic的东西,但我想用Python语言来做,而不是创建编译器. 应该有一种使用词典的解决方案,其格式如下:

dict = {
"if": "hehe"
"elif": "haha"
"else": "hihi"
}

但我不知道如何让它在代码中工作,这样我就可以在之后用这种"新语言"编写代码

推荐答案

我没有在这上面花太多时间(它还可以改进),这是我第一次使用tokenize模块,但这是我想出来的.

当我在寻找一个python解析器时,我找到了这个模块,它基本上解析python代码并对其进行分类,从那里你可以对它做任何你想做的事情.

from token import DEDENT, INDENT, NEWLINE
import tokenize
result = ''

names = {
    'if': 'hehe',
    'elif': 'haha',
    'else': 'hihi',
    # Add here all the other names, that you want to change, and don't worry about a name occurring inside a string it will not be changed
}
# open the script you want to encrypt in a tokenize file object
with tokenize.open('z.py') as f:
    # create a new tokenize object and feed it the lines
    tokens = tokenize.generate_tokens(f.readline)
    # for every token in all the tokens in the file:
    for token in tokens:
        if names.get(token[1]): # token[1] is the string of the token i.e 'if', 'for', '\n', 'or' etc
            result += names.get(token[1]) + ' '
        elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
            result += token[1]
            print(result)
        else:
            result += token[1] + ' '


with open('z.py', 'w') as f:
    f.write(result)

update

前面的代码只进行了编码,只需稍加改动,就可以重复使用相同的代码来对脚本进行解码和编码:

from token import DEDENT, INDENT, NEWLINE
import tokenize

encode_name = {
    'if': 'hehe',
    'elif': 'haha',
    'else': 'hihi',
}

def code(name, encode=True):
    if encode:
        names = name
    else:
        # flip the dict, keys become values and vice versa
        names = {v: k for k, v in name.items()}
    
    result = ''
    with tokenize.open('z.py') as f:
        tokens = tokenize.generate_tokens(f.readline)
        for token in tokens:
            if names.get(token[1]):
                result += names.get(token[1]) + ' '
            elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
                result += token[1]
            else:
                result += token[1] + ' '

    with open('z.py', 'w') as f:
        f.write(result)


code(encode_name, encode = False)

查看official docs的更多信息我自己不是专家,但请不要犹豫,在这里问任何问题.

我很乐意帮忙 祝你好运,编码快乐

Python相关问答推荐

使用numpy提取数据块

Polars LazyFrame在收集后未返回指定的模式顺序

Pystata:从Python并行运行stata实例

如何根据参数推断对象的返回类型?

当从Docker的--env-file参数读取Python中的环境变量时,每个\n都会添加一个\'.如何没有额外的?

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

如何将一个动态分配的C数组转换为Numpy数组,并在C扩展模块中返回给Python

在Python argparse包中添加formatter_class MetavarTypeHelpFormatter时, - help不再工作""""

python中csv. Dictreader. fieldname的类型是什么?'

Pandas:计算中间时间条目的总时间增量

找到相对于列表索引的当前最大值列表""

如何在Python中使用Iscolc迭代器实现观察者模式?

Python类型提示:对于一个可以迭代的变量,我应该使用什么?

如何使用pytest在traceback中找到特定的异常

当我定义一个继承的类时,我可以避免使用`metaclass=`吗?

TypeError:';Locator';对象无法在PlayWriter中使用.first()调用

Pandas:使列中的列表大小与另一列中的列表大小相同

Groupby并在组内比较单独行上的两个时间戳

Django-修改后的管理表单返回对象而不是文本

Pandas:新列,从列表中采样,基于列值