英文:
Parsing file, ignoring comments and blank lines
问题
正如标题所说,我正在尝试解析一个文件,但忽略注释(以#
开头)或空行。我已经尝试为此编写了一个系统,但它似乎总是忽略了应该忽略注释和/或空行的部分。
lines := strings.Split(d, "\n")
var output map[string]bool = make(map[string]bool)
for _, line := range lines {
if strings.HasPrefix(line, "#") != true {
output[line] = true
} else if len(line) > 0 {
output[line] = true
}
}
当运行时(这是一个函数的一部分),它输出如下内容:
这是输入(d
变量):
Minecraft
Zerg Rush
Pokemon
# Hello
这是打印输出(output
变量):
map[Minecraft:true Zerg Rush:true Pokemon:true :true # Hello:true]
我的问题是它仍然保留了""
和"# Hello"
的值,这意味着某些地方出错了,我还没有找到原因。
那么,我在哪里出错了,导致它保留了不正确的值?
英文:
As the title says, I am trying to parse a file but ignore comments (started with #
) or blank lines. I have tried to make a system for this, yet it always seems to ignore that it should be ignoring comments and/or blank lines.
lines := strings.Split(d, "\n")
var output map[string]bool = make(map[string]bool)
for _, line := range lines {
if strings.HasPrefix(line, "#") != true {
output = true
} else if len(line) > 0 {
output = true
}
}
When run (this is part of a function), it outputs the following
This is the input ('d' variable):
Minecraft
Zerg Rush
Pokemon
# Hello
This is the output when printed ('output' variable):
map[Minecraft:true Zerg Rush:true Pokemon:true :true # Hello:true]
My issue here is that it still keeps the "" and "# Hello" values, meaning that something failed, something I haven't been able to figure out.
So, what am I doing wrong that this keeps the improper values?
答案1
得分: 3
len(line) > 0
将对"# Hello"
行返回true,因此它将被添加到output
中。
目前,您正在添加不以#开头的行或者不为空的行。您需要只添加同时满足这两个条件的行:
if !strings.HasPrefix(line, "#") && len(line) > 0 {
output[line] = true
}
英文:
len(line) > 0
will be true for the "# Hello"
line, so it will get added to output
.
Currently, you are adding lines that either don't start with a # or are not empty. You need to only add lines that satisfy both conditions:
if !strings.HasPrefix(line, "#") && len(line) > 0 {
output = true
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论