擅长:python、mysql、java
<p>看起来您正在尝试lex,因此我建议您研究专门为此目的设计的模块,例如<a href="http://www.dabeaz.com/ply/ply.html" rel="nofollow">^{<cd1>}</a>。你知道吗</p>
<p>是的。你知道吗</p>
<p>尽管如此,我认为您在本例中的思路是正确的,但是您缺少了一些<strong>递归<strong>(为了使这些更通用的lexer):</p>
<pre><code>def splitting1(z):
for char in "*/+-":
if char in z:
position = z.find(char)
text_before_operator= (z[:position]).strip()
text_after_operator= (z[position+1:]).strip()
return (char, splitting1(text_before_operator), splitting1(text_after_operator))
return ("number", z)
</code></pre>
<p>找到最左边的运算符而不考虑其优先级(即省略运算符优先级)的一种方法是重新排列您迭代的内容:</p>
<pre><code>def splitting2(z):
for char in z:
if char in "*/+-":
position = z.find(char)
text_before_operator= (z[:position]).strip()
text_after_operator= (z[position+1:]).strip()
return (char, splitting2(text_before_operator), splitting2(text_after_operator))
return ("number", z)
</code></pre>
<p><em>注意,这些函数返回与原始函数不同的结果。</em></p>