我正在尝试在目录中的文件中搜索或搜索特定单词,并将所有文件中的每个实例转换为大写。
我想跟踪找到该词的文件以及它在这些文件中出现的次数。
到目前为止,我能够读取文件的内容。
如何从主函数发送一个参数来搜索文件并将这些实例替换为大写?
这是我目前所拥有的:
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)
}
这意味着:
- 而不是定义一个全局函数
visit
(它不能用任何额外的参数调用,比如yourWord
) - 在调用
filepath.Walk
之前定义一个callback
函数 ( function literal )
在“Codewalk: First-Class Functions in Go”中查看更多信息
函数文字和闭包
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/