-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathget_image_chars.py
More file actions
82 lines (66 loc) · 2.84 KB
/
get_image_chars.py
File metadata and controls
82 lines (66 loc) · 2.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
#encoding=utf-8
import argparse
from pathlib import Path
IMG_EXTENSIONS = {'.jpg', '.jpeg', '.png', '.pbm', '.pgm', '.ppm', '.bmp', '.gif', '.tif', '.tiff', '.svg', '.kra', '.psd'}
def save_set_to_file(sorted_set, filename_output):
try:
with open(filename_output, 'w', encoding='utf-8') as f:
full_text = "".join(chr(item) for item in sorted_set)
f.write(full_text)
except Exception as e:
print(f"寫入檔案時發生錯誤: {e}")
def main(args):
source_folder = Path(args.input)
if not source_folder.is_dir():
print("輸入的路徑不是資料夾")
return
source_unicode_set = set()
for file_path in source_folder.iterdir():
if file_path.is_file() and file_path.suffix.lower() in IMG_EXTENSIONS:
char_string = file_path.stem
try:
if args.filename_rule == 'unicode_int':
char_int = int(char_string)
elif args.filename_rule == 'unicode_hex':
char_int = int(char_string, 16)
else:
if len(char_string) > 0:
char_int = ord(char_string[0])
else:
continue
if 0 <= char_int < 0x110000:
source_unicode_set.add(char_int)
except ValueError:
continue
if source_unicode_set:
sorted_set = sorted(list(source_unicode_set))
if args.output:
filename_output = args.output
else:
# 使用 resolve() 先轉成絕對路徑再抓 name
# 這樣輸入 . 的時候就會拿到實際的資料夾名稱
folder_name = source_folder.resolve().name
# 預防在根目錄執行導致名稱為空的情況
if not folder_name:
folder_name = "output"
filename_output = f"{folder_name}.txt"
save_set_to_file(sorted_set, filename_output)
print(f"輸入目錄: {source_folder}")
print(f"輸出檔案: {filename_output}")
print(f"解析格式: {args.filename_rule}")
print(f"字元數量: {len(sorted_set)}")
else:
print("資料夾內沒有符合條件的圖片檔案或解析失敗")
def cli():
parser = argparse.ArgumentParser(description="從圖片檔名獲取字型清單")
parser.add_argument("input", help="輸入目錄路徑")
parser.add_argument("--output", "-o", help="輸出文件路徑", default=None)
parser.add_argument("--filename_rule", "-f",
choices=['char', 'unicode_hex', 'unicode_int'],
default="unicode_int",
help="檔名解析格式")
args = parser.parse_args()
main(args)
if __name__ == "__main__":
cli()