Python 的标记化将所有找到的标记的位置返回为两个元组 (startRow, startCol) 和 (endRow, endCol)。
有没有办法将位置作为从字符串开头的偏移量返回?也就是说,我想摆脱 (row, col) 而只支持“偏移”。
请您参考如下方法:
tokenize 没有一个内置的。
如果您可以访问分词器使用的同一组行,则可以遍历累积的“X 行之前的行总长度”并将其存储到列表中,然后使用它将行值转换为附加补偿。
例如:
import tokenize
def tokens_with_offset(path):
line_offsets = []
line_offset_accum = 0
with open(path) as f:
for line in f:
line_offsets.append(line_offset_accum)
line_offset_accum += len(line)
with open(path) as f:
for ttype, tstring, tbegin, tend, tline in tokenize.generate_tokens(f.readline):
offset_begin = line_offsets[tbegin[0]] + tbegin[1]
offset_end = line_offsets[tend[0]] + tend[1]
yield ttype, tstring, offset_begin, offset_end, tline
(注意:尚未测试此代码,它更像是一般概念的示例。)
