【发布时间】:2021-11-22 17:08:01
【问题描述】:
我想忽略像{ comments } 和// comments 这样的每条评论。
我有一个名为 peek 的指针,它逐个字符地检查我的字符串。我知道如何忽略换行符、制表符和空格,但我不知道如何忽略 cmets。
string = """ beGIn west WEST north//comment1 \n
north north west East east south\n
// comment west\n
{\n
comment\n
}\n end
"""
tokens = []
tmp = ''
for i, peek in enumerate(string.lower()):
if peek == ' ' or peek == '\n':
tokens.append(tmp)
# ignoing WS's and comments
if(len(tmp)>0):
print(tmp)
tmp = ''
else:
tmp += peek
这是我的结果:
begin
west
west
north//
comment1
north
north
west
east
east
south
{
comment2
}
end
如您所见,空格会被忽略,但 cmets 不会。
我怎样才能得到如下结果?
begin
west
west
north
north
north
west
east
east
south
end
【问题讨论】:
-
对于基本实现,检查当前字符是否为
{,如果是,则忽略所有内容,直到关闭},然后照常进行。 -
@AndrewMcClement 这就是问题我不知道如何实现这一步,我不知道我是否应该使用正则表达式或其他东西,另一个问题是输入字符串是否有多行 cmets ,我应该怎么做。
-
只需使用
if peek == '{': skip = True elif peek == '}': skip = False并在if not skip: ... your code中运行if/else的其余部分
标签: python compiler-construction lexical-analysis