Các đoạn code Python mình hay sử dụng

Chào cả nhà bài này mình sẽ note lại các đoạn code python hữu ích mình đã nhờ AI viết hộ. Các đoạn code mình sẽ để trong cặp lệnh: <pre><code> để hiển thị khác đi so với nội dung cho dễ đọc, nên chỉ cần copy code bạn nhìn thấy là được:

Code để tự động gộp 2 phụ đề phim lại với nhau thành 1 phụ đề

(dùng khi bạn có 1 phụ đề phim tiếng việt và 1 phụ đề phim tiếng anh)

from pathlib import Path
def merge_srt(file1, file2, outfile):
    lines1 = Path(file1).read_text(encoding="utf-8").splitlines()
    lines2 = Path(file2).read_text(encoding="utf-8").splitlines()

    merged = []
    i = j = 0
    while i < len(lines1) and j < len(lines2):
        if lines1[i].isdigit() and lines2[j].isdigit():
            # Chỉ số phụ đề
            merged.append(lines1[i])
            i += 1; j += 1
            # Thời gian
            merged.append(lines1[i])
            i += 1; j += 1
            # Nội dung: nối 2 dòng phụ đề
            text1, text2 = [], []
            while i < len(lines1) and lines1[i] != "":
                text1.append(lines1[i]); i += 1
            while j < len(lines2) and lines2[j] != "":
                text2.append(lines2[j]); j += 1
            merged.append(" ".join(text1))
            merged.append(" ".join(text2))
            merged.append("")
            # Bỏ qua dòng trống
            if i < len(lines1) and lines1[i] == "": i += 1
            if j < len(lines2) and lines2[j] == "": j += 1
        else:
            i += 1; j += 1

    Path(outfile).write_text("\n".join(merged), encoding="utf-8")
    print(f"Đã tạo file song ngữ: {outfile}")


if __name__ == "__main__":
    merge_srt("sub_en.srt", "sub_vi.srt", "sub_bilingual.srt")

Khi sử dụng đoạn code trên bạn lưu ý đặt tên file là “sub_en.srt”, “sub_vi.srt”, và lưu tên file code là: merge_subs.py. Khi chạy bạn chỉ cần mở cửa sổ terminal và gõ: python merge_subs.py

Code để tự động thêm dấu gạch ngang vào tên file ảnh

Dùng khi bạn muốn đổi tên nhiều file ảnh, code sẽ giữ nguyên tên thay khoảng trống giữa các từ bằng dấu “-”

import os
import re
import unicodedata

def slugify(filename):
    name, ext = os.path.splitext(filename)

    # Bỏ dấu tiếng Việt
    name = unicodedata.normalize('NFKD', name)
    name = name.encode('ascii', 'ignore').decode('ascii')

    # Chữ thường
    name = name.lower()

    # Thay ký tự không phải chữ & số thành dấu -
    name = re.sub(r'[^a-z0-9]+', '-', name)

    # Xóa dấu - dư ở đầu/cuối
    name = name.strip('-')

    return name + ext.lower()

# Thư mục chứa ảnh (mặc định là thư mục hiện tại)
folder_path = os.getcwd()

image_extensions = ('.jpg', '.jpeg', '.png', '.webp')

for filename in os.listdir(folder_path):
    if filename.lower().endswith(image_extensions):
        new_name = slugify(filename)
        if new_name != filename:
            os.rename(
                os.path.join(folder_path, filename),
                os.path.join(folder_path, new_name)
            )
            print(f"Đã đổi: {filename} → {new_name}")

Đoạn code trên bạn lưu thành tên file.py rồi đặt trong thư mục có chứa ảnh.

Leave a Comment