如何正确拆分代码字符串
How to split code string properly
我正在尝试为 Python 中的 Java 编写一个基本的词法分析器。我现在面临的问题是将一行字符串拆分为 words/tokens.
示例:
if (x < 3)
{
x = 3;
}
else
{
x = 0;
}
我想要return这样的列表:
["if", "(", "x", "<", "3", ")", ...
但我的代码 returning
["if", "(x", "<", "3)"]
我的代码:
for line in code.readlines():
for word in line.split():
print word
我搜索了一个解决方案,但只找到了使用正则表达式的解决方案,有没有不用正则表达式的方法?因为我不知道如何使用它们而且我现在没有足够的时间来学习它...
任何帮助将不胜感激...
Python string .split()
函数,默认以白色 space 分隔字符串, return 包含任何不包含 space 的混合字符的列表秒。我的简单建议是在使用 .split()
函数之前用新的两侧 spaces 符号替换符号字符:
for line in code.readlines():
for sign in '({[<+-=*/%;>]})':
line = line.replace(sign, ' %s ' % sign)
for word in line.split():
print word
我正在尝试为 Python 中的 Java 编写一个基本的词法分析器。我现在面临的问题是将一行字符串拆分为 words/tokens.
示例:
if (x < 3)
{
x = 3;
}
else
{
x = 0;
}
我想要return这样的列表:
["if", "(", "x", "<", "3", ")", ...
但我的代码 returning
["if", "(x", "<", "3)"]
我的代码:
for line in code.readlines():
for word in line.split():
print word
我搜索了一个解决方案,但只找到了使用正则表达式的解决方案,有没有不用正则表达式的方法?因为我不知道如何使用它们而且我现在没有足够的时间来学习它...
任何帮助将不胜感激...
Python string .split()
函数,默认以白色 space 分隔字符串, return 包含任何不包含 space 的混合字符的列表秒。我的简单建议是在使用 .split()
函数之前用新的两侧 spaces 符号替换符号字符:
for line in code.readlines():
for sign in '({[<+-=*/%;>]})':
line = line.replace(sign, ' %s ' % sign)
for word in line.split():
print word