gpt4 book ai didi

python - 将 python 源代码解析为 html - 引号

转载 作者:行者123 更新时间:2023-12-01 05:56:19 25 4
gpt4 key购买 nike

我正在开发一个工具,可以将 python 源代码解析为一个漂亮的 html 文件。基本上,它逐行读取 python 文件,查看该行以确定其中的内容,然后添加正确的 <span>带有颜色、换行符等的标签。

我已经了解了程序的一般结构,现在我正在制作实际读取字符串并返回 HTML 丰富字符串的所有函数。

我一直在解析其中包含引号的字符串,即:

x = 'hello there'  
if x == 'example "quotes" inside quotes' and y == 'another example':

到目前为止,我的工作是枚举一个字符串来获取单引号的索引,将它们作为列表返回,然后使用两个 while 循环将正确的 html 标签放在正确的位置。当字符串中有一个单引号时,它似乎工作得很好,但是当我在一行上引入两个引号,或者引号内的引号,或者最后一个由 '\'' 组成的字符串时,一切都崩溃了。

看来这条路是死路一条。我现在正在考虑求助.split() , shlex ,或re并将字符串分解为列表并尝试使用它。
我真的很感激提示、指示和任何建议。

编辑:另外,为了更清楚,我需要将 HTML 标签放在字符串中的正确位置。对于更复杂的字符串,使用字符串索引不会产生太多结果。

最佳答案

您可以使用tokenize.generate_tokens:

import tokenize
import token
import io

text = '''
x = 'hello there'
if x == 'example "quotes" inside quotes' and y == 'another example': pass
'''


tokens = tokenize.generate_tokens(io.BytesIO(text).readline)
for toknum, tokval, (srow, scol), (erow, ecol), line in tokens:
tokname = token.tok_name[toknum]
print(tokname, tokval)

产量

('NL', '\n')
('NAME', 'x')
('OP', '=')
('STRING', "'hello there'")
('NEWLINE', '\n')
('NAME', 'if')
('NAME', 'x')
('OP', '==')
('STRING', '\'example "quotes" inside quotes\'')
('NAME', 'and')
('NAME', 'y')
('OP', '==')
('STRING', "'another example'")
('OP', ':')
('NAME', 'pass')
('NEWLINE', '\n')
('ENDMARKER', '')

从这里,您可以根据每个 token 的类型 (tokname) 输出适当的 HTML。

关于python - 将 python 源代码解析为 html - 引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12467903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com