以下是一个用Go语言编写的将EPUB文件转换为TXT文件的代码示例:
package main
import (
"archive/zip"
"fmt"
"io/ioutil"
"os"
"strings"
)
func main() {
if len(os.Args) < 2 {
fmt.Println("Usage: go run epub_to_txt.go <epub_file>")
os.Exit(1)
}
epubFile := os.Args[1]
r, err := zip.OpenReader(epubFile)
if err != nil {
fmt.Println("Failed to open EPUB file:", err)
os.Exit(1)
}
defer r.Close()
var txtFile string
for _, f := range r.File {
if strings.HasSuffix(f.Name, ".txt") {
txtFile = f.Name
break
}
}
if txtFile == "" {
fmt.Println("No TXT file found in EPUB file")
os.Exit(1)
}
f, err := r.Open(txtFile)
if err != nil {
fmt.Println("Failed to open TXT file in EPUB file:", err)
os.Exit(1)
}
defer f.Close()
content, err := ioutil.ReadAll(f)
if err != nil {
fmt.Println("Failed to read TXT file in EPUB file:", err)
os.Exit(1)
}
err = ioutil.WriteFile(strings.TrimSuffix(txtFile, ".txt")+".txt", content, 0644)
if err != nil {
fmt.Println("Failed to write TXT file:", err)
os.Exit(1)
}
fmt.Println("TXT file successfully created")
}
使用方法:
- 将上述代码保存为
epub_to_txt.go
- 打开命令行终端并进入代码所在的目录
- 运行
go run epub_to_txt.go <epub_file>
,其中<epub_file>
是待转换的EPUB文件路径
运行成功后,将在同一目录下生成一个同名的TXT文件。