首页 > 解决方案 > 如何让 textX 模型将第五个测试用例视为单独的行

问题描述

将第五个测试行添加到输入变量时失败的示例代码。把第五行去掉,模型就可以工作了。

from textx import metamodel_from_str

mm = metamodel_from_str('''
File:
    lines+=Line;

Line:
    startwords=Startwords
    dirp=DirPhrase?
    words=Words?
    command=Commands?
;

Startwords: 
    (StartKeywords | Signs)?;

StartKeywords:
    'bag';

Commands:
    ('sleep over'|'walk');

Words:
    words+=Word?;

Word:
    !DirType !Commands ID;

Signs:
    signs+=Sign;

Sign:
    !Commands !StartKeywords Word;

DirPhrase:
    dirtyp=DirType
    dir=Dir
;

DirType:
    'fast';

Dir:
    ('left'|'right')+;

''')

input = '''
bag  sun kiss  sleep over
animal walk
big horse walk
big white cow fast left
little black cow fast right
'''
#little black cow fast right


model = mm.model_from_str(input, debug=False)

l = model.lines[0]
assert l.startwords == 'bag'
assert l.words.words == ['sun', 'kiss']
assert l.command == 'sleep over'

l = model.lines[1]
assert l.startwords.signs == ['animal']
assert l.words == None
assert l.command == 'walk'

l = model.lines[2]
assert l.startwords.signs == ['big', 'horse']
assert l.words == None
assert l.command == 'walk'

l = model.lines[3]
assert l.startwords.signs == ['big', 'white', 'cow']
assert l.words == None
assert l.command == None
assert l.dirp.dirtyp == 'fast'
assert l.dirp.dir == 'left'

if len(model.lines) == 5:
    l = model.lines[4]
    assert l.startwords.signs == ['little', 'black', 'cow']
    assert l.words == None
    assert l.command == None
    assert l.dirp.dirtyp == 'fast'
    assert l.dirp.dir == 'right'

正在发生的事情是l.words在第四输入行处理期间以某种方式读取第五输入行。那里的断言失败,因为l.words应该是None. 我尝试过使用[eolterm]修饰符,但是这会产生其他错误。

标签: pythontextx

解决方案


[eolterm]使用以下代码部分解决了此问题

Words:
    words+=Word?;

对此

Words:
    words+=Word[eolterm];

[eolterm]不喜欢?所以不得不删除那个。随着它的消失,它就像一个冠军。


推荐阅读