希望了解 Python 的 tokenize模块。我有兴趣在给定的 python 源文件(如下所示)上调用 tokenize.tokenize 方法,并使用文档中提到的 5 元组获取其标记化输出。
# Python source file
import os
class Test():
"""
This class holds latitude, longitude, depth and magnitude data.
"""
def __init__(self, latitude, longitude, depth, magnitude):
self.latitude = latitude
self.longitude = longitude
self.depth = depth
self.magnitude = magnitude
def __str__(self):
# -1 is for detection of missing data
depth = self.depth
if depth == -1:
depth = 'unknown'
magnitude = self.magnitude
if magnitude == -1:
depth = 'unknown'
return "M{0}, {1} km, lat {2}\N{DEGREE SIGN} lon {3}\N{DEGREE SIGN}".format(magnitude, depth, self.latitude, self.longitude)
不幸的是,example考虑到我对 Python 缺乏经验,文档中的内容不够清楚,无法使其正常工作。另外,我在网上找不到任何相关的有用示例代码。
任何简单可行的代码示例将不胜感激。 此外,如果您知道有用的在线 Material 以及 tokenize 模块及其方法的示例/说明,那将是很棒的。
请您参考如下方法:
tokenize.tokenize 是一个生成器,它将产生多个对应于源中每个标记的 5 元组。
with open('/path/to/src.py', 'rb') as f:
for five_tuple in tokenize.tokenize(f.readline):
print(five_tuple.type)
print(five_tuple.string)
print(five_tuple.start)
print(five_tuple.end)
print(five_tuple.line)
