我尝试将Tcl列表翻译为python列表。
有两个问题:
{{12 34}}
未正确翻译。Python 3代码:
import tkinter
class TclInterpreter(object):
def __init__(self):
self._tcl = tkinter.Tcl()
def eval(self, tcl_cmd):
return self._tcl.eval(tcl_cmd)
class TclPyListTranslator(object):
def __init__(self, tcl):
self._tcl = tcl
def to_py(self, tcl_list, dtype=str):
# convert a Tcl List to python list, also convert elements of each leaf
# node to dtype
self._tcl.eval("set tcl_list %s" % tcl_list)
numItems = int(self._tcl.eval("llength $tcl_list"))
if numItems > 1:
result = [self._tcl.eval("lindex $tcl_list %d" % i) for i in range(
numItems)]
for i in range(numItems):
result[i] = self.to_py("{" + result[i] + "}", dtype)
else:
result = dtype(self._tcl.eval("lindex $tcl_list %d" % 0))
return result
inter = TclInterpreter()
translator = TclPyListTranslator(inter)
tcl_list = "{12 {{12 34}} {56 {78 {11 12} 10}}}"
# prints ['12', '12 34', ['56', ['78', ['11', '12'], '10']]]
# The '12 34' is incorrect
print(translator.to_py(tcl_list))
# does not run
print(translator.to_py(tcl_list, int))
答案 0 :(得分:1)
处理此问题的最简单方法是在Tcl端(本机上理解Tcl列表)获取代码,以生成Python值的字符串形式,然后在Python中生成eval
。然而,复杂的部分是Tcl的类型系统与Python的完全不同(我不打算解释它,因为它是一个非常复杂和技术性的论点) ,决定嵌套列表结构的叶子在哪里是非平凡的。需要一些假设。有了这些假设,我们可以在没有太多代码的情况下做相当不错的工作。
你需要的Tcl代码是这样的(在你需要整数的叶子的情况下):
proc toPythonList {value} {
if {[string is integer -strict $value]} {
return $value
}
set result "\["
foreach item $value {
append result [toPythonList $item] ", "
}
append result "\]"
return $result
}
这意味着你可以做到这一点(我已经为不同类型的树叶添加了非常简单的版本的修改版本):
class TclPyListTranslator(object):
def __init__(self, tcl):
self._tcl = tcl
self._tcl.eval("""
proc isLeaf.int {value} {
string is integer -strict $value
}
proc isLeaf.str {value} {
expr {![string match "{*}" $value]}
}
proc toPythonLeaf.int {value} { return $value }
proc toPythonLeaf.str {value} { return "\"$value\"" }
proc toPythonList {value dtype} {
if {[isLeaf.$dtype $value]} {
return [toPythonLeaf.$dtype $value]
}
set result "\["
foreach item $value {
append result [toPythonList $item] ", "
}
append result "\]"
return $result
}
""")
def to_py(self, tcl_list, dtype=str):
# convert a Tcl List to python list
return eval(self._tcl.eval("toPythonList %s %s" % (tcl_list, dtype.__name__))
警告:上面的代码应该有效,但我无法对其进行测试,因为我没有在任何Python解释器中配置tkinter。但这些作品本身就是有效的,所以我有理由相信。
答案 1 :(得分:1)
Python解析器:
def add_element(cache, element):
if element != '':
cache[-1].append(element)
return ''
def parse(raw_tcl_list):
out = []
cache = [out]
element = ''
escape = False
for char in tcl_list:
if escape:
element += char
escape = False
elif char == "\\":
escape = True
elif char in [" ", "\t", "\r", "\n"]:
element = add_element(cache, element)
elif char == "{":
a = []
cache[-1].append(a)
cache.append(a)
elif char == "}":
element = add_element(cache, element)
cache.pop()
else:
element += char
return out[0]
import pprint
pprint.pprint(
parse("{ 12 apple {100} {} {{12 34}} \n {56\n { \\{78 {11 12 11} 10}}}"))
输出:
['12',
'apple',
['100'],
[],
[['12', '34']],
['56', ['{78', ['11', '12', '11'], '10']]]