【问题标题】:Grabbing all 'special words' in python抓取python中的所有“特殊词”
【发布时间】:2020-06-07 09:39:20
【问题描述】:

要获取python中的关键字,我可以使用keywords

import keyword
keyword.keywords
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

但是,我希望在 python 中找到所有“特殊单词”以进行语法突出显示。比如单词dirinput(raw_input如果python2)、setlist等。python中是否有存放所有“特殊词”的地方——关键字和其他地方—— - 为了语法高亮?

【问题讨论】:

  • 语法高亮不是 Python 的一部分。这完全取决于您的语法荧光笔。您无法从 Python 中检索此信息,因为它不取决于 Python。
  • 您可能会发现import builtins; dir(builtins) 很有帮助。另见:stackoverflow.com/questions/9642087/…
  • @user2357112supportsMonica:但是 Python 当然可以用来识别这些词,我认为这就是问题的重点。
  • @MarkMeyer:在 Python2 中似乎不起作用。
  • @user2357112supportsMonica 我的印象是该操作试图创建一个突出显示功能。

标签: python


【解决方案1】:

这些被称为内置函数。从this answer 你可以使用这样的方法。您也有类型(例如intlist)。将这些添加到您的关键字中,您应该有相当完整的覆盖范围。

import builtins
import inspect

builtin_functions = [name for name, function in sorted(vars(builtins).items()) if inspect.isbuiltin(function) or inspect.isfunction(function)]
types = [name for name, function in sorted(vars(builtins).items()) if type(function) == type]

或者对于 python 2

import __builtin__
import inspect

builtin_functions = [name for name, function in sorted(vars(__builtin__).items()) if inspect.isbuiltin(function) or inspect.isfunction(function)]
types = [name for name, function in sorted(vars(__builtin__).items()) if type(function) == type]

【讨论】:

  • 您发布了一个尚未实际测试过的答案?
  • 这不包括 intzip 之类的内容。
  • 现在编辑为也包含类型(intlist,...)
猜你喜欢
  • 2016-07-22
  • 1970-01-01
  • 1970-01-01
  • 2021-09-25
  • 1970-01-01
  • 1970-01-01
  • 2018-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多