2012-10-10 202 views
4

我遇到了pexpect问题。我试图从tralics读取乳胶方程并发出MATHML表示,像这样抢输出:pexpect捕获输出

1 ~/ % tralics --interactivemath 
This is tralics 2.14.5, a LaTeX to XML translator, running on tlocal 
Copyright INRIA/MIAOU/APICS/MARELLE 2002-2012, Jos\'e Grimm 
Licensed under the CeCILL Free Software Licensing Agreement 
Starting translation of file texput.tex. 
No configuration file. 
> $x+y=z$ 
<formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi> <mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula> 
> 

所以我尝试使用Pexpect的获得公式:

import pexpect 
c = pexpect.spawn('tralics --interactivemath') 
c.expect('>') 
c.sendline('$x+y=z$') 
s = c.read_nonblocking(size=2000) 
print s 

输出有公式,但在开始的原始输入和一些控制字符结尾:

"x+y=z$\r\n<formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi><mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula>\r\n\r> \x1b[K" 

我可以清洁输出字符串,但我一定是失去了一些东西BA SIC。有没有更简洁的方法来获得MathML?

回答

4

从我了解你正试图从Pexpect的得到这样的:

<formula type='inline'><math xmlns='http://www.w3.org/1998/Math/MathML'><mrow><mi>x</mi> <mo>+</mo><mi>y</mi><mo>=</mo><mi>z</mi></mrow></math></formula> 

可以为了获得期望的结果使用正则表达式,而不是“>”为匹配。这是最简单的例子:

c.expect("<formula.*formula>"); 

之后,您可以通过调用Pexpect的的匹配属性访问匹配的字符串:

print c.match 

您也可以尝试不同的正则表达式,由于事实我发布的一个是贪婪的,如果公式很大,它可能会阻碍你的执行时间。

+1

谢谢!为了完整性,我做了'c.expect(“”)',然后用'print c.match.group()'得到结果。为了准备下一个公式,我会'c.expect('>')并重复。 – Tim

+0

我很高兴它帮助:) –