要从一个目录中提取出章节的名称,可以使用以下代码示例来实现:
package main
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
)
func main() {
dirPath := "world" // 目录路径
files, err := ioutil.ReadDir(dirPath)
if err != nil {
fmt.Println("读取目录失败:", err)
os.Exit(1)
}
for _, file := range files {
if !file.IsDir() { // 忽略非目录文件
continue
}
chapterName := strings.TrimPrefix(file.Name(), "chapter_")
fmt.Println(chapterName)
}
}
上述代码假设world
目录下存放了多个以chapter_
开头的子目录,例如chapter_01
, chapter_02
等。该代码会遍历这些子目录,并打印出去除前缀chapter_
后的章节名称。你可以根据实际需求进行相应的修改和调整。
内容由零声教学AI助手提供,问题来源于学员提问