file-io - 读取一个golang文件并用大写字母替换单词搜索

标签 file-io go str-replace

我正在尝试在目录中的文件中搜索或搜索特定单词,并将所有文件中的每个实例转换为大写。

我想跟踪找到该词的文件以及它在这些文件中出现的次数。

到目前为止,我能够读取文件的内容。
如何从主函数发送一个参数来搜索文件并将这些实例替换为大写?

这是我目前所拥有的:

func visit(path string, fi os.FileInfo, err error) error {

    if err!=nil{
        return err
     }

     if !!fi.IsDir(){
        return nil //
     }

      matched, err := filepath.Match("*.txt", fi.Name())

      if err !=nil{
        fmt.Println(err)
        return err
      }

      if matched{
      read,err:= ioutil.ReadFile(path)
      fmt.Println(read)
      check(err)
      fmt.Println(path) }

  return nil
} 

func main() {

  err := filepath.Walk(".", visit)
}

最佳答案

您可以使用 callback 函数文本看到的变量,由 filepath.Walk 使用,作为闭包。
例如参见“GOLANG: Walk Directory Tree and Process Files”。

func main() {

    var yourWord := "a word"

    callback := func(path string, fi os.FileInfo, err error) error {
            // do something with yourWord!
    }

    filepath.Walk(".", callback)

}

这意味着:

函数文字和闭包

Anonymous functions can be declared in Go.
Function literals are closures: they inherit the scope of the function in which they are declared.
They may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.

在您的情况下,“回调”函数文字将从之前定义的变量 yourWord 继承。


注意:要调用的函数是strings.ToUpper() ,而不是 strings.toUpper()

关于file-io - 读取一个golang文件并用大写字母替换单词搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24804625/

相关文章:

php - 我过度使用 str_replace 并且想不出更好的方法

C 程序将文件 io 传递给函数

C++:自定义对象序列化/反序列化失败

go - 简单如果不工作 go 模板

xml - 如何从 XML 元素中获取文本(结构标签)?

python - 如何保持替换字符串的数量

python - python 中的输出按字典排序

c - 在多进程环境中读取文件时意外的 EOF

go - 在 Windows 上输出转义序列

java - Java 中的字符串替换冒险