Oosayam commited on
Commit
5551649
1 Parent(s): 8156697

Upload search_and_copy.py

Browse files
Files changed (1) hide show
  1. search_and_copy.py +88 -0
search_and_copy.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import shutil
3
+ import tkinter as tk
4
+ from tkinter import filedialog, messagebox
5
+
6
+ def process_files(words, output_directory):
7
+ # 生成輸出的檔名,將逗號替換為底線
8
+ output_filename = "_".join(words) + ".txt"
9
+
10
+ # 確保檔案名稱最後不會有下劃線
11
+ if output_filename.endswith("_.txt"):
12
+ output_filename = output_filename[:-5] + ".txt"
13
+
14
+ # 如果目錄不存在,創建目錄
15
+ if not os.path.exists(output_directory):
16
+ os.makedirs(output_directory)
17
+
18
+ # 準備輸出的檔案
19
+ temp_output_filename = "temp_" + output_filename
20
+ with open(temp_output_filename, 'w', encoding='utf-8') as outfile:
21
+ # 瀏覽當前目錄下的所有檔案
22
+ for filename in os.listdir('.'):
23
+ # 只處理純文字檔案
24
+ if filename.endswith('.txt') and filename != temp_output_filename:
25
+ try:
26
+ with open(filename, 'r', encoding='utf-8') as infile:
27
+ # 處理每一行
28
+ for line in infile:
29
+ # 檢查行是否包含所有的輸入單詞
30
+ if all(word in line for word in words):
31
+ # 將符合條件的行寫入輸出檔案
32
+ outfile.write(line)
33
+ except Exception as e:
34
+ print(f"無法讀取檔案 {filename}: {e}")
35
+
36
+ # 將臨時檔案移動到目標目錄
37
+ final_output_path = os.path.join(output_directory, output_filename)
38
+ shutil.move(temp_output_filename, final_output_path)
39
+
40
+ messagebox.showinfo("完成", f"符合條件的行已寫入檔案 {final_output_path}")
41
+
42
+ def on_process():
43
+ input_words = input_entry.get()
44
+ words = [word.strip() for word in input_words.split(",")]
45
+
46
+ # 檢查單詞是否超過十個
47
+ if len(words) > 10:
48
+ messagebox.showerror("錯誤", "輸入的單詞不能超過十個")
49
+ return
50
+
51
+ output_directory = output_dir_entry.get().strip()
52
+
53
+ # 如果沒有輸入,使用預設目錄
54
+ if not output_directory:
55
+ output_directory = r"I:\sd-forge\extensions\sd-dynamic-prompts\wildcards"
56
+
57
+ process_files(words, output_directory)
58
+
59
+ def browse_directory():
60
+ directory = filedialog.askdirectory()
61
+ if directory:
62
+ output_dir_entry.delete(0, tk.END)
63
+ output_dir_entry.insert(0, directory)
64
+
65
+ # 創建主窗口
66
+ root = tk.Tk()
67
+ root.title("詞彙檢測工具")
68
+
69
+ # 輸入詞彙框
70
+ tk.Label(root, text="請輸入一組單詞(最多十個單詞,用逗號分隔):").pack(pady=5)
71
+ input_entry = tk.Entry(root, width=50)
72
+ input_entry.pack(pady=5)
73
+
74
+ # 輸出目錄框
75
+ tk.Label(root, text="請輸入輸出目錄(如果不存在,將會自動創建):").pack(pady=5)
76
+ output_dir_entry = tk.Entry(root, width=50)
77
+ output_dir_entry.pack(pady=5)
78
+
79
+ # 瀏覽目錄按鈕
80
+ browse_button = tk.Button(root, text="瀏覽...", command=browse_directory)
81
+ browse_button.pack(pady=5)
82
+
83
+ # 開始處理按鈕
84
+ process_button = tk.Button(root, text="開始處理", command=on_process)
85
+ process_button.pack(pady=20)
86
+
87
+ # 運行主循環
88
+ root.mainloop()