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().

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

报告相同问题?

悬赏问题

  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效