解析文件,忽略注释和空行。

huangapple go评论68阅读模式
英文:

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 }

huangapple
  • 本文由 发表于 2016年4月18日 05:03:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/36682205.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定