附件表示一个树结构,我想将其转换为java源代码,将树表示为嵌套的if语句
STOP_WORDS > 0
| NEXT_TYPE > 5: X
| NEXT_TYPE <= 5: Y
STOP_WORDS <= 0
…
If (STOP_WORDS > 0)
{
If (NEXT_TYPE > 5)
{
Return X
}
If ( NEXT_TYPE <= 5)
{
Return Y
}
}
If (STOP_WORDS <= 0)
{
….
}
如您所见,使用管道(|)符号的缩进级别表示父子关系 你可以用Java编写这个程序,或者你喜欢用你认为合适的任何其他语言编写。
下面是我需要转换为If语句的文本文件:
STOP_WORDS > 0
| NEXT_TYPE > 5: 5
| NEXT_TYPE <= 5: 1
STOP_WORDS <= 0
| STREET_TYE > 0
| | PREVIOUS_TYPE > 5: 2
| | PREVIOUS_TYPE <= 5
| | | NEXT_TYPE > 5: 2
| | | NEXT_TYPE <= 5: 5
| STREET_TYE <= 0
| | PERSON_TITLE > 0
| | | NEXT_TYPE <= 5: 4
| | | NEXT_TYPE > 5: 5
| | PERSON_TITLE <= 0
| | | SURNAME > 0
| | | | PREVIOUS_TYPE <= 4: 3
| | | | PREVIOUS_TYPE > 4: 5
| | | SURNAME <= 0
| | | | FIRST_NAME > 0
| | | | | NEXT_TYPE <= 5: 0
| | | | | NEXT_TYPE > 5: 5
| | | | FIRST_NAME <= 0
| | | | | TOKEN_LENGTH <= 1
| | | | | | NEXT_TYPE <= 4: 0
| | | | | | NEXT_TYPE > 4
| | | | | | | NEXT_TYPE <= 5: 1
| | | | | | | NEXT_TYPE > 5: 5
| | | | | TOKEN_LENGTH >1
| | | | | | NEXT_TYPE > 4: 5
| | | | | | NEXT_TYPE <= 4: 0
| | | | | | | PREVIOUS_TYPE <= 1: 4
| | | | | | | PREVIOUS_TYPE >1
| | | | | | | | PREVIOUS_TYPE >3: 4
| | | | | | | | PREVIOUS_TYPE <= 3: 5
我的问题是我找不到跟踪以前的If语句以及何时关闭它们的逻辑。正如您所看到的,每条线都有很多管道(|),有时候管道更少,有时管道更多。我找不到它的逻辑。
任何帮助都将不胜感激。
答案 0 :(得分:0)
你的问题非常不清楚,但这是一个开始
barometer = 0
with open('path/to/input') as infile:
for line in infile:
barometer += delta
line = ''.join(itertools.dropwhile(lambda c: c in ' |', line))
if ":" in line:
cond, act = line.split(":",1)
print "If (%s) { Return %s }" %(cond, act)
else:
delta = barometer - sum(1 for i in itertools.takewhile(lambda c: c in ' |', line))
if delta < 0:
print " {}"[delta/abs(delta)]*abs(delta)
print "If (%s) {" %cond
我现在必须去睡觉了,但这应该让你开始,至少
答案 1 :(得分:0)
with open('input.txt') as f:
indent = 8
prev_depth = -1
closes = []
for line in f:
line = line.strip()
if not line: continue
depth = line.count('|')
while prev_depth >= depth:
prev_depth -= 1
print(closes.pop())
pad = ' ' * (depth*indent)
print(pad + 'If ({})'.format(line.lstrip('| ').split(':', 1)[0]))
print(pad + '{')
closes.append(pad + '}')
if ':' in line:
pad2 = ' ' * ((depth+1)*indent)
print(pad2 + 'Return {}'.format(line[line.find(':')+1:].strip()))
prev_depth = depth
while closes:
print(closes.pop())