2012-10-10 160 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

我很高興它幫助:) –