【问题标题】:Tokenize python source code examples (in Python)标记 python 源代码示例(在 Python 中)
【发布时间】:2016-05-24 17:55:17
【问题描述】:

希望了解 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 缺乏经验,无法使其正常工作。另外,我在网上找不到任何相关的有用示例代码。

任何简单可行的代码示例将不胜感激。 此外,如果您知道有用的在线材料以及 tokenize 模块及其方法的示例/说明,那就太好了。

【问题讨论】:

    标签: python python-3.x tokenize


    【解决方案1】:

    tokenize.tokenize是一个生成器,它将yield多个5-tuples对应source中的每个token。

    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)
    

    【讨论】:

    • 感谢您的回答。但是,我没有得到令牌的名称,例如STRINGOP 等。我错过了什么吗?
    • 它们是元组中的第一项,但它们是一个 int,而不是一个字符串。您必须将它们与 tokenize 模块中的全局静态变量与 if five_tuple.type == tokenize.OP 进行比较
    • 我明白了,我该如何与更多的结构性标记(例如 if 语句和其他关键字)进行比较??
    • 您将不得不自己做一些工作。只需打印出所有标记元组,然后查看 if 语句的类型。标记元组包括代码字符串标记出现的整行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-15
    • 2020-11-04
    • 1970-01-01
    • 2011-01-25
    • 2014-10-04
    • 1970-01-01
    • 2018-07-17
    相关资源
    最近更新 更多