登录
首页 >  Golang >  Go问答

在 Go 中搜索句子中的单词

来源:stackoverflow

时间:2024-02-27 22:24:25 374浏览 收藏

一分耕耘,一分收获!既然都打开这篇《在 Go 中搜索句子中的单词》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

问题内容

在 python 中我有这样的代码

search_words_nontexas = ["tx", "texas", "houston"]
pass = any(word in title for word in search_words_nontexas)

在 go 中,我一直在尝试这个

firstpass := strings.containsany("title", searchwordsnontexas)

我收到一个关于参数不正确的错误(如下所示)。 go 中的等价物是什么?

cannot use searchWordsNonTexas (type [10]string) as type string in 
argument to strings.ContainsAny

解决方案


在 python 中我有代码。 go 中的等价物是什么?

在 go(一种较低级语言)中编写自己的函数。

例如,

package main

import (
    "fmt"
    "strings"
    "unicode"
)

// look for list of words in a sentence.
func wordsinsentence(words []string, sentence string) []string {
    var in []string

    dict := make(map[string]string, len(words))
    for _, word := range words {
        dict[strings.tolower(word)] = word
    }

    f := func(r rune) bool { return !unicode.isletter(r) }
    for _, word := range strings.fieldsfunc(sentence, f) {
        if word, ok := dict[strings.tolower(word)]; ok {
            in = append(in, word)
            delete(dict, word)
        }
    }

    return in
}

func main() {
    words := []string{"tx", "texas", "houston"}
    sentence := "the texas song yellow rose of texas was sung in houston, tx."
    in := wordsinsentence(words, sentence)
    fmt.println(in)
}

演示:https://play.golang.org/p/CwSLiDnq928

输出:

[texas houston tx]

到这里,我们也就讲完了《在 Go 中搜索句子中的单词》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

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