File size: 3,234 Bytes
5551649 |
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 83 84 85 86 87 88 89 |
import os
import shutil
import tkinter as tk
from tkinter import filedialog, messagebox
def process_files(words, output_directory):
# 生成輸出的檔名,將逗號替換為底線
output_filename = "_".join(words) + ".txt"
# 確保檔案名稱最後不會有下劃線
if output_filename.endswith("_.txt"):
output_filename = output_filename[:-5] + ".txt"
# 如果目錄不存在,創建目錄
if not os.path.exists(output_directory):
os.makedirs(output_directory)
# 準備輸出的檔案
temp_output_filename = "temp_" + output_filename
with open(temp_output_filename, 'w', encoding='utf-8') as outfile:
# 瀏覽當前目錄下的所有檔案
for filename in os.listdir('.'):
# 只處理純文字檔案
if filename.endswith('.txt') and filename != temp_output_filename:
try:
with open(filename, 'r', encoding='utf-8') as infile:
# 處理每一行
for line in infile:
# 檢查行是否包含所有的輸入單詞
if all(word in line for word in words):
# 將符合條件的行寫入輸出檔案
outfile.write(line)
except Exception as e:
print(f"無法讀取檔案 {filename}: {e}")
# 將臨時檔案移動到目標目錄
final_output_path = os.path.join(output_directory, output_filename)
shutil.move(temp_output_filename, final_output_path)
messagebox.showinfo("完成", f"符合條件的行已寫入檔案 {final_output_path}")
def on_process():
input_words = input_entry.get()
words = [word.strip() for word in input_words.split(",")]
# 檢查單詞是否超過十個
if len(words) > 10:
messagebox.showerror("錯誤", "輸入的單詞不能超過十個")
return
output_directory = output_dir_entry.get().strip()
# 如果沒有輸入,使用預設目錄
if not output_directory:
output_directory = r"I:\sd-forge\extensions\sd-dynamic-prompts\wildcards"
process_files(words, output_directory)
def browse_directory():
directory = filedialog.askdirectory()
if directory:
output_dir_entry.delete(0, tk.END)
output_dir_entry.insert(0, directory)
# 創建主窗口
root = tk.Tk()
root.title("詞彙檢測工具")
# 輸入詞彙框
tk.Label(root, text="請輸入一組單詞(最多十個單詞,用逗號分隔):").pack(pady=5)
input_entry = tk.Entry(root, width=50)
input_entry.pack(pady=5)
# 輸出目錄框
tk.Label(root, text="請輸入輸出目錄(如果不存在,將會自動創建):").pack(pady=5)
output_dir_entry = tk.Entry(root, width=50)
output_dir_entry.pack(pady=5)
# 瀏覽目錄按鈕
browse_button = tk.Button(root, text="瀏覽...", command=browse_directory)
browse_button.pack(pady=5)
# 開始處理按鈕
process_button = tk.Button(root, text="開始處理", command=on_process)
process_button.pack(pady=20)
# 運行主循環
root.mainloop()
|