duanmiyang6201 2016-05-09 12:53
浏览 186

Golang重命名Unicode文件名

How to rename a file in unicode format, the gaps? When you try to rename the standard library function, the file is not located.

Old: /usr/home/spouk/go/src/simple/Agraba - I Know You Are Smiling Now (Original Mix).mp4 New: /usr/home/spouk/go/src/simple/Agraba_-_I_Know_You_Are_Smiling_Now__Original_Mix_.mp4 [RENAME] rename Agraba - I Know You Are Smiling Now (Original Mix).mp4 /usr/home/spouk/go/src/simple/Agraba_-_I_Know_You_Are_Smiling_Now__Original_Mix_.mp4: no such file or directory

Someone tell me what to use or where to get acquainted with the direction of solution to this problem. Tnx.

package main

import (
    "flag"
    d "github.com/fiam/gounidecode/unidecode"
    "fmt"
    "path/filepath"
    "os"
    "strings"
    "strconv"
    "os/exec"
)

type (
    File struct {
        OriginPath  string
        ConvertPath string
    }
    FilesStack struct {
        Files   []File
        InPath  string
        OutPath string
    }
)

func NewFilesStack() *FilesStack {
    n := new(FilesStack)
    n.Files = []File{}
    return n
}
func (f *FilesStack) RuneToAscii(r rune) string {
    if r < 128 {
        return string(r)
    } else {
        return "\\u" + strconv.FormatInt(int64(r), 16)
    }
}
func (f *FilesStack) TransliterCyr(str string) string {
    var result []string
    for _, sym := range d.Unidecode(str) {
        if (f.RuneToAscii(sym) == " ") || (f.RuneToAscii(sym) == "'") || (f.RuneToAscii(sym) == "`") || (f.RuneToAscii(sym) == ")") || (f.RuneToAscii(sym) == "(") {
            result = append(result, "_")
        } else {
            result = append(result, f.RuneToAscii(sym))
        }
    }
    return strings.Join(result, "")
}
func (f *FilesStack) walkFunction(path string, info os.FileInfo, err error) error {

    if !info.IsDir() {
        res, err := filepath.Abs(filepath.Dir(info.Name()))
        if err != nil {
            fmt.Printf(err.Error())
        }
        ext := filepath.Ext(info.Name())
        if ext == ".mp4" {
            file := new(File)
            //make new file name
            oldfile := filepath.Join(res, info.Name())
            newname := filepath.Join(res, f.TransliterCyr(info.Name()))

            file.OriginPath = filepath.Join(res, newname)
            fmt.Printf("Old: %s
New: %s
", oldfile, newname)

            //rename file
            if err_rename := os.Rename(info.Name(), newname); err_rename != nil {
                fmt.Printf("[RENAME] %s
", err_rename.Error())
            }

            tmpname := []string{}
            name := strings.TrimRight(info.Name(), filepath.Ext(info.Name()))
            for _, sym := range name {
                if f.RuneToAscii(sym) != " " {
                    tmpname = append(tmpname, string(sym))
                }
            }
            word := strings.Join(tmpname, "")
            oo, _ := filepath.Abs(f.OutPath)
            rr := strings.Join([]string{f.TransliterCyr(word), ".mp3"}, "")
            //fmt.Printf("Res: %v %v
", rr, word)
            file.ConvertPath = filepath.Join(oo, rr)
            //fmt.Printf("Infile: %v
", file.OriginPath)
            //fmt.Printf("Outfile: %v
", file.ConvertPath)
            f.Files = append(f.Files, *file)
        }
    }
    return nil
}
func (f *FilesStack) ParseFilesmp4() {
    //парсинг файлов
    if err := filepath.Walk(f.InPath, f.walkFunction); err != nil {
        fmt.Printf(err.Error())
    }
    //конвертация

    for _, file := range f.Files {
        fmt.Printf("Start convertation %s 
", file.OriginPath)
        command := fmt.Sprintf("ffmpeg -i %s -f mp3 %s", file.OriginPath, file.ConvertPath)
        //fmt.Printf("Command %v
", command)
        cmd, err_convert := exec.Command(command).Output()
        if err_convert != nil {
            fmt.Printf(err_convert.Error())
        }

        fmt.Printf("Result convert: %v
", cmd)
    }
}

// note, that variables are pointers
var (
    inpath = flag.String("inpath", ".", "директория для поиска всех файлов с расширением .mp4")
    outpath = flag.String("outpath", ".", "директория для сохранения .mp3")
)

func main() {
    //make files structy
    f := NewFilesStack()
    //parse arguments
    flag.Parse()
    fmt.Printf("inpath: %s
outpath: %s
", *inpath, *outpath)
    //set arguments
    f.InPath = *inpath
    f.OutPath = *outpath
    f.ParseFilesmp4()
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 乘性高斯噪声在深度学习网络中的应用
    • ¥15 运筹学排序问题中的在线排序
    • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
    • ¥30 求一段fortran代码用IVF编译运行的结果
    • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
    • ¥15 C++ 头文件/宏冲突问题解决
    • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
    • ¥50 安卓adb backup备份子用户应用数据失败
    • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
    • ¥30 python代码,帮调试,帮帮忙吧