尽管有字符串变量,但如何将代码文件拆分为单词

时间:2016-06-20 15:54:21

标签: python

使用python,如何将包含方法,变量等代码的文件拆分为单词,但将代码的字符串变量保留为一个单元字符串?

例如:   在文件中给出以下python代码:

def example():
    a = 5
    b = "Hello World"

结果应为:

['def', 'example', '(', ')', ':', 'a', '=', '5', 'b', '=', '"Hello World"']

其中" Hello World"是一个单一的标记。

...谢谢

1 个答案:

答案 0 :(得分:0)

您可以使用shlex模块。

示例,对于fule:

采取以下文字:

This string has embedded "double quotes" and 'single quotes' in it,
and even "a 'nested example'".

使用shlex库,我们构造了一个简单的词法解析器:

import shlex
import sys

if len(sys.argv) != 2:
    print 'Please specify one filename on the command line.'
    sys.exit(1)

filename = sys.argv[1]
body = file(filename, 'rt').read()
print 'ORIGINAL:', repr(body)
print

print 'TOKENS:'
lexer = shlex.shlex(body)
for token in lexer:
    print repr(token)

这会生成输出:

ORIGINAL: 'This string has embedded "double quotes" and \'single quotes\' in it,\nand even "a \'nested example\'".\n'

TOKENS:
'This'
'string'
'has'
'embedded'
'"double quotes"'
'and'
"'single quotes'"
'in'
'it'
','
'and'
'even'
'"a \'nested example\'"'
'.'

可以找到更多信息和一个很好的教程here