douluxia0606 2014-07-17 13:14
浏览 139
已采纳

读取golang文件并将单词搜索替换为大写

I am trying to search for or a particular words in the files in a directory and and convert each of its instance in all the file in Uppercase.

I want to keep track of the file where the word was found and how many time it appeared in those file.

So far I am able to read the content of the file.
How do send an argument then from the main function to search through the file and replace those instance into upper case?

This is what I have so far:

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)
}
  • 写回答

1条回答 默认 最新

  • dongliu5475 2014-07-17 13:44
    关注

    You can use a variable which is seen by a callback function literal, used by filepath.Walk, as a closure.
    See for instance "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)
    
    }
    

    That means:

    Function literals and closures

    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.

    In your case, the 'callback' function literal will inherit from the variable yourWord defined before.


    Note: the function to call is strings.ToUpper(), not strings.toUpper().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题