【问题标题】:How do I use this tokenizer to tokenize a string of code?如何使用这个标记器来标记一串代码?
【发布时间】:2021-09-13 12:38:44
【问题描述】:

所以我有这样一行代码:

'    return classInformation.buildEnrollment(request, nextview, auth, false);'

I want to use the tokenizer found here 生成如下令牌:

"['INDENT', 'NAME', 'NAME' DOT', 'NAME', LPAR', 'NAME', 'COMMA', 'NAME', 'COMMA', 'NAME', 'COMMA', 'NAME', 'RPAR', 'SEMI', 'DEDENT']"

我不知道获取这些令牌的代码是什么样的,我遇到的问题是我需要编写这样一行代码:

"'password=hd92732'"

看起来像这样:

"['NAME', 'EQUAL', 'NAME', 'DEDENT']"

而不是这个:

"['STRING', 'DEDENT']"

【问题讨论】:

    标签: python tokenize cpython


    【解决方案1】:
    from token import tok_name
    from tokenize import tokenize
    
    with open("ff", 'wb') as f:
    f.write(
        b'    return classInformation.buildEnrollment(request, nextview, auth, false);\n'
        b'    return classInformation.buildEnrollment(request, nextview, auth, false);\n'
        b'    return classInformation.buildEnrollment(request, nextview, auth, false);\n'
    )
    
    readline = open("ff", 'rb').__next__
    print(','.join([tok_name[l.type] for l in tokenize(readline)]))
    

    您将获得一个“NEWLINE”标记来分隔每一行

    【讨论】:

    • 好的。那么现在我该如何处理多行文件呢?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-07
    相关资源
    最近更新 更多