我把关键词分类如下:
Keywords_33=[('File_2', ['with', 'as']),
('Module_2', ['from', 'import']),
('Constant_3', {'bool': ['False', 'True'],
'none': ['None']}),
('Operator_4', {'boolean_operation': {'or', 'and', 'not'},
'comparison': {'is'}}),
('Container_operation_2', ['in', 'del']),
('Klass_1', ['class']),
('Function_7',['lambda', 'def', 'pass',
'global', 'nonlocal',
'return', 'yield']),
('Repetition_4', ['while', 'for', 'continue', 'break']),
('Condition_3', ['if', 'elif', 'else']),
('Debug_2', ['assert', 'raise']),
('Exception_3', ['try', 'except', 'finally'])]
我打算确认每一个关键字在没有任何遗留类别的地方。
我认为最方便的方法是首先将Keywords_33
转换为字符串。你知道吗
from keyword import kwlist
In [55]: print(kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
In [54]: from keyword import kwlist
...: s = str(Keywords_33)
...: [keyword for keyword in kwlist if keyword not in s]
...:
Out[54]: []
# It indicate no keyword left
如何优雅地完成这样的任务?你知道吗
依赖dict/list嵌套列表的字符串表示有点危险,因为您可以匹配不需要的单词/子字符串(例如
elif
包含if
),因此如果列表包含elif
,它也会匹配if
。一些聪明的re.findall
可以工作,在引号之间提取文本,但这仍然是一种技巧。你知道吗相反,您可以创建dict值的列表或列表(取决于类型),从而生成:
然后在不规则的项目列表(Flatten (an irregular) list of lists)上使用展开方法,转换为
set
并双向减法/相交:在这种情况下
set(kwlist) == my_keywords
我区分,如果第二个元素是列表还是字典。(注意,在本例中它是有效的,因为每个元组正好包含两个元素)。在list情况下,我可以轻松地遍历并比较元素是否在列表中。对于dictionary,如果值在kwlist中,我可以遍历dictionary的值并进行比较
相关问题 更多 >
编程相关推荐