我喜欢使用pyparsing模块在python中创建这种性质的解析器。Pyparsing是一个解析器组合器库;您可以通过组合其他解析器来构造解析器。下面是一个使用pyparsing的示例解析器,它将解析您的输入数据(它无法解析任何prolog事实,但我认为这将是一个不错的起点):import pyparsing as pp
#relationship will refer to 'track' in all of your examples
relationship = pp.Word(pp.alphas).setResultsName('relationship')
number = pp.Word(pp.nums + '.')
variable = pp.Word(pp.alphas)
# an argument to a relationship can be either a number or a variable
argument = number | variable
# arguments are a delimited list of 'argument' surrounded by parenthesis
arguments= (pp.Suppress('(') + pp.delimitedList(argument) +
pp.Suppress(')')).setResultsName('arguments')
# a fact is composed of a relationship and it's arguments
# (I'm aware it's actually more complicated than this