[Curve Kernel] Curve:translate Chinese annotations in the Curve into English annotations(Medium)
题目 idea:
-
Use a Go script to recursively traverse all directories and files in the given directory.
-
Based on different file extensions, use corresponding regular expressions to extract comment contents.
-
If the comment content contains Chinese comments, call a translation API to replace the Chinese comment content with English comment content.
-
Finally, write the modified file content back to the file.
Here is an example of a simple script (without using a translation API, only simple text replacement is done here):
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"regexp"
"strings"
)
// Traverse all directories and files
func visit(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Println("Error accessing path:", err)
return nil
}
if !info.IsDir() {
ext := filepath.Ext(path) // Get the file extension
// Handle comments parsing and processing based on different file extensions
if ext == ".go" || ext == ".h" || ext == ".cpp" {
file, err := os.Open(path)
if err != nil {
fmt.Println("Unable to open file:", err)
return nil
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
fmt.Println("Unable to read file: ", err)
return nil
}
fileContent := string(content)
// Create regular expression pattern
regex := `\/\*[\s\S]*?\*\/|\/\/.*`
re := regexp.MustCompile(regex)
commentsGrp := re.FindAllString(fileContent, -1)
for _, comment := range commentsGrp {
if isContainCh(comment) {
fmt.Println(comment)
comment_en := transCh2En(comment)
fileContent = strings.Replace(fileContent, comment, comment_en, 1)
}
}
// Write the modified file content back to the file
err = ioutil.WriteFile(path, []byte(fileContent), info.Mode())
if err != nil {
fmt.Println("Unable to write file:", err)
return nil
}
}
}
return nil
}
func main() {
root := "./test"
err := filepath.Walk(root, visit)
if err != nil {
fmt.Println("Error walking file:", err)
return
}
}
// Check if the comment contains Chinese characters
func isContainCh(comment string) bool {
for _, r := range comment {
if r >= 0x4e00 && r <= 0x9fff {
return true
}
}
return false
}
// 4. Translate Chinese comments to English comments using an API
func transCh2En(comment_ch string) string {
comment_en := "/* this is english comment */"
return comment_en
}