close

powerful-programming-language-word-python-450w-401797897

(圖片來源)

一、使用 hanziconv 繁簡轉換工具

STEP1. 安裝

pip install hanziconv

STEP2. 繁簡轉換使用

1. 繁簡轉換功能 (※ 此案例僅使用到此功能)

from hanziconv import HanziConv
print(HanziConv.toSimplified('繁簡轉換器'))  # 繁简转换器
print(HanziConv.toTraditional('繁简转换器')) # 繁簡轉換器

 

2. 繁簡比對功能

from hanziconv import HanziConv
str1 = 'mix English and Chinese. 繁簡轉換器'
str2 = 'mix English and Chinese. 繁简转换器'
str3 = 'mix Chinese and English. 繁简转换器'

HanziConv.same(str1, str2) # True
HanziConv.same(str2, str3) # False

 

二、python3.6 環境下使用 os.walk

使用範例:

import os
for root,dirs,files in os.walk(r"C:\Users\ME\Desktop\Python project\pachong\scrapy\baichuan2\保险"):
    """
    os.walk() 方法用于通过在目录树中游走输出在目录中的文件名,向上或者向下。
    os.walk() 方法是一个简单易用的文件、目录遍历器,可以帮助我们高效的处理文件、目录方面的事情。
    语法规则:os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
    top -- 是你所要遍历的目录的地址, 返回的是一个三元组(root,dirs,files)。
    root 所指的是当前正在遍历的这个文件夹的本身的地址
    dirs 是一个 list ,内容是该文件夹中所有的目录的名字(不包括子目录)
    files 同样是 list , 内容是该文件夹中所有的文件(不包括子目录)
    topdown --可选,为 True,则优先遍历 top 目录,否则优先遍历 top 的子目录(默认为开启)。如果 topdown 参数为 True,walk 会遍历top文件夹,与top 文件夹中每一个子目录。
    onerror -- 可选, 需要一个 callable 对象,当 walk 需要异常时,会调用。
    followlinks -- 可选, 如果为 True,则会遍历目录下的快捷方式(linux 下是 symbolic link)实际所指的目录(默认关闭)。
    """
    print (root)
    for dir in dirs:
        print (os.path.join(root,dir))
    for file in files:

 

三、批次目錄檔名繁簡轉換

代碼:

import os.path
from hanziconv import HanziConv

rootdir = "D:/Users/shianlin/Desktop/集邦/99.other/Laravel 5.4快速開發簡書網站"

for root,dirs,files in os.walk(rootdir):
    for dir in dirs:
        newName = HanziConv.toTraditional(dir)
        os.rename(os.path.join(root,dir), os.path.join(root,newName))
        print('folder: ' + dir + ' to ' + newName)
    for file in files:
        newName = HanziConv.toTraditional(file)
        os.rename(os.path.join(root, file), os.path.join(root, newName))
        print('file: ' + file + ' to ' + newName)

 

參考:

python实现汉字简繁体相互转换-hanziconv-0.2.1
hanziconv package
在python3.6环境下使用os.walk遍历所有的中文文件夹,并且打印对应的地址
Python 3 – os.rename() Method 

 

 

 

 

 

arrow
arrow

    Mayuge 發表在 痞客邦 留言(0) 人氣()