登录
首页 >  Golang >  Go问答

切分字符串: 使用不等于逻辑判断首字符

来源:stackoverflow

时间:2024-03-29 12:12:27 208浏览 收藏

你在学习Golang相关的知识吗?本文《切分字符串: 使用不等于逻辑判断首字符》,主要介绍的内容就涉及到,如果你想提升自己的开发能力,就不要错过这篇文章,大家要知道编程理论基础和实战操作都是不可或缺的哦!

问题内容

我有一个 .dat 文件,它是包含大约 30 万行的字典/同义词库

对于每个单词,其下面在字符串开头的括号中包含单词的行是同义词库的替代项,括号中的单词是类型。所以是名词或形容词。例如:

acceptant|1
(adj)|acceptive|receptive 
acceptation|3
(noun)|acceptance
(noun)|word meaning|word sense|sense|signified
(noun)|adoption|acceptance|espousal|blessing|approval|approving
accepted|6
(adj)|recognized|recognised|acknowledged 
(adj)|undisputed|uncontroversial |noncontroversial
(adj)|standard 
(adj)|acceptable|standard |received
(adj)|established |constituted
(adj)|received|conventional 
accepting|1
(adj)|acceptive

上面的字典中有 4 个单词,但每个单词都有多个不同的词库条目

我想使用以下方式分割字符串:

strings.Split(dictionary, !"(")

表示除“(”字符之外的任何内容。这是因为它是一本包含俚语和缩写词之类的内容丰富的字典。但我不知道如何使用不等于运算符

有谁知道如何使用不等于逻辑的分割?或者有人可以提出一些聪明的替代想法吗?


解决方案


package main

import (
    "bufio"
    "fmt"
    "os"
    "strings"
)

func main() {

    file, _ := os.open("dic.dat")
    scanner := bufio.newscanner(file)
    for scanner.scan() {
        line := scanner.text()
        if strings.hasprefix(line, "(") {
            continue
        }
        fmt.println(line)
    }

}

@mostafasolati 的解决方案可以通过更高效地编写来改进。

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "os"
)

func main() {
    file, _ := os.open("dic.dat")
    scanner := bufio.newscanner(file)
    for scanner.scan() {
        data := scanner.bytes()
        if bytes.hasprefix(data, []byte("(")) {
            continue
        }
        line := scanner.text()
        fmt.println(line)
    }
}

输出:

acceptant|1
acceptation|3
accepted|6
accepting|1

按照设计,go 代码应该是高效的。 go 标准库测试包包含基准测试功能。

避免不必要的转换和分配非常重要。例如,将从文件读取的字节片转换为字符串、分配和副本。

在这种情况下,我们只需要将接受的数据转换为字符串即可。例如,与文本相比,更喜欢字节。

$ go test dict_test.go -bench=.
benchmarktext-4      500    2486306 ns/op    898528 b/op    14170 allocs/op
benchmarkbytes-4    1000    1489828 ns/op     34080 b/op      609 allocs/op
$

基准数据示例:

key: aback.
syn: backwards, rearwards, aft, abaft, astern, behind, back.
ant: onwards, forwards, ahead, before, afront, beyond, afore.
=
key: abandon.
syn: leave, forsake, desert, renounce, cease, relinquish,
discontinue, castoff, resign, retire, quit, forego, forswear,
depart from, vacate, surrender, abjure, repudiate.
ant: pursue, prosecute, undertake, seek, court, cherish, favor,
protect, claim, maintain, defend, advocate, retain, support, uphold,
occupy, haunt, hold, assert, vindicate, keep.
=

dict_test.go

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "io/ioutil"
    "os"
    "strings"
    "testing"
)

func BenchmarkText(b *testing.B) {
    b.ReportAllocs()
    for N := 0; N < b.N; N++ {
        file := bytes.NewReader(benchData)
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            line := scanner.Text()
            if !strings.HasPrefix(line, "KEY") {
                continue
            }
            _ = line // process line
        }
        if err := scanner.Err(); err != nil {
            b.Fatal(err)
        }
    }
}

func BenchmarkBytes(b *testing.B) {
    b.ReportAllocs()
    for N := 0; N < b.N; N++ {
        file := bytes.NewReader(benchData)
        scanner := bufio.NewScanner(file)
        for scanner.Scan() {
            data := scanner.Bytes()
            if !bytes.HasPrefix(data, []byte("KEY")) {
                continue
            }
            line := scanner.Text()
            _ = line // process line
        }
        if err := scanner.Err(); err != nil {
            b.Fatal(err)
        }
    }
}

var benchData = func() []byte {
    // A Complete Dictionary of Synonyms and Antonyms by Samuel Fallows
    // http://www.gutenberg.org/files/51155/51155-0.txt
    data, err := ioutil.ReadFile(`/home/peter/dictionary.51155-0.txt`)
    if err != nil {
        panic(err)
    }
    return data
}()

本篇关于《切分字符串: 使用不等于逻辑判断首字符》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>