Skip to main content
 首页 » 编程设计

python之如何在 python tokenizer 的每一行之后执行操作

2024年10月01日6artech

我正在使用 python tokenize处理python源文件的模块。代码如下所示:

raw_list = [] 
words_list = [] 
g = tokenize.generate_tokens(file.readline) 
for toknum, tokval, _, _, line in g: 
    if toknum == tokenize.NAME and tokval not in PYTHON_KEYWORD: 
        words_list.append(tokval) 

我知道我可以使用 line 变量引用当前行。我想在每一行之后将 words_list 附加到 raw_list 。我怎样才能做到这一点?具体来说,如何在 line 值更改后每次执行追加操作?

我正在考虑使用 next 方法,但我看不到任何干净的方法。

例如,

假设我的输入源文件只包含一行:

from __future__ import print_function 

并且有四个标记:from、__future__、import 和 print_function。现在,对于g,对于每个token,都会返回5元组,即“token type”、“token string”、“(srow, scol)”、“(erow, ecol)” ”。例如,代币 __future__ 将有

NAME, (1,2), (1,5), "from __future__ import print_function" 

"from __future__ import print_function" 将被读入变量 line。现在,__future__ 和 print_function 都将 line 变量设置为 “从 __future__ 导入 print_function”。只有 __future__ 和 print_function 不是 python 保留关键字,因此 words_list 将以 ['__future__', 'print_function'].

我的问题是如何仅在 line 值更改(即下一行字符串)时将 words_list 附加到 raw_list。

谢谢!

请您参考如下方法:

感谢@ juanpa.arrivillaga精彩的答案。明确检查 tokenize.NEWLINE 是否有效。代码如下所示:

raw_list = [] 
words_list = [] 
g = tokenize.generate_tokens(file.readline) 
for toknum, tokval, _, _, line in g: 
    if toknum == tokenize.NAME and tokval not in PYTHON_KEYWORD: 
        words_list.append(tokval) 
    if toknum == tokenize.NEWLINE: 
        raw_list.append(words_list) 
        words_list = []