[Python] Chuyển tên file tiếng Việt có dấu thành không dấu

0
295

Code đổi tên tệp/file số lượng lớn trong thư mục/folder:

  • Từ tiếng việt có dấu sang không dấu
  • Từ khoảng trắng ” ” thành gạch ngang “-“
import os
import re
"""List ra các ký tự cần thay đổi"""
patterns = {
    '[àáảãạăắằẵặẳâầấậẫẩ]': 'a',
    '[đ]': 'd',
    '[èéẻẽẹêềếểễệ]': 'e',
    '[ìíỉĩị]': 'i',
    '[òóỏõọôồốổỗộơờớởỡợ]': 'o',
    '[ùúủũụưừứửữự]': 'u',
    ' ': '-',
    '[ỳýỷỹỵ]': 'y'
}
"""
Hàm Convert from 'Tieng Viet co dau' thanh 'Tieng Viet khong dau'
Convert dau cach " " thanh dau "-"
text: input string to be converted
Return: string converted
"""
def convert(text):
    output = text
    for regex, replace in patterns.items():
        output = re.sub(regex, replace, output)
        # deal with upper case
        output = re.sub(regex.upper(), replace.upper(), output)
    return output

"""đường dẫn folder chứa các file cần đổi tên"""
folder_path = "E:\link-folder"
files = os.listdir(folder_path)
"""vòng lập đổi tên tất cả các file trong folder"""
for file in files:
    link=os.path.join(folder_path, file)
    newlink= os.path.join(folder_path, convert(file))
    oldpath = link    
    newpath = newlink
    os.rename(oldpath, newpath)

-longnh-

Link rút gọn của bài viết: https://longnh.com/9IuLY