20270721
This commit is contained in:
8
.idea/.gitignore
generated
vendored
Normal file
8
.idea/.gitignore
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
14
.idea/deployment.xml
generated
Normal file
14
.idea/deployment.xml
generated
Normal file
@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="PublishConfigData" remoteFilesAllowedToDisappearOnAutoupload="false">
|
||||
<serverData>
|
||||
<paths name="root@192.168.1.102:22 password">
|
||||
<serverdata>
|
||||
<mappings>
|
||||
<mapping local="$PROJECT_DIR$" web="/" />
|
||||
</mappings>
|
||||
</serverdata>
|
||||
</paths>
|
||||
</serverData>
|
||||
</component>
|
||||
</project>
|
||||
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
6
.idea/inspectionProfiles/profiles_settings.xml
generated
Normal file
@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
7
.idea/misc.xml
generated
Normal file
7
.idea/misc.xml
generated
Normal file
@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="Python 3.13 (pythonProject1)" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.13 (pythonProject1)" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
8
.idea/modules.xml
generated
Normal file
8
.idea/modules.xml
generated
Normal file
@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/pythonProject1.iml" filepath="$PROJECT_DIR$/.idea/pythonProject1.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
10
.idea/pythonProject1.iml
generated
Normal file
10
.idea/pythonProject1.iml
generated
Normal file
@ -0,0 +1,10 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/.venv" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
6
.idea/vcs.xml
generated
Normal file
6
.idea/vcs.xml
generated
Normal file
@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$" vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
688
main.py
Normal file
688
main.py
Normal file
@ -0,0 +1,688 @@
|
||||
import os
|
||||
import PyPDF2
|
||||
import docx
|
||||
import pandas as pd
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, messagebox
|
||||
from tkinter import ttk
|
||||
import threading
|
||||
import time
|
||||
import zipfile
|
||||
import py7zr
|
||||
import rarfile
|
||||
import webbrowser
|
||||
|
||||
# 全局变量用于控制搜索状态
|
||||
pause_flag = threading.Event()
|
||||
stop_flag = threading.Event()
|
||||
|
||||
|
||||
def search_pdf(file_path, keyword):
|
||||
try:
|
||||
with open(file_path, 'rb') as file:
|
||||
reader = PyPDF2.PdfReader(file)
|
||||
matches = []
|
||||
for page_num, page in enumerate(reader.pages, start=1):
|
||||
text = page.extract_text()
|
||||
if keyword in text:
|
||||
matches.append({'page': page_num, 'value': text})
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading PDF {file_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_word(file_path, keyword):
|
||||
try:
|
||||
doc = docx.Document(file_path)
|
||||
matches = []
|
||||
# 遍历段落
|
||||
for para_num, para in enumerate(doc.paragraphs, start=1):
|
||||
if keyword in para.text:
|
||||
matches.append({'paragraph': para_num, 'value': para.text})
|
||||
# 遍历表格
|
||||
for table_num, table in enumerate(doc.tables, start=1):
|
||||
for row_num, row in enumerate(table.rows, start=1):
|
||||
for cell_num, cell in enumerate(row.cells, start=1):
|
||||
if keyword in cell.text:
|
||||
matches.append({
|
||||
'table': table_num,
|
||||
'row': row_num,
|
||||
'cell': cell_num,
|
||||
'value': cell.text
|
||||
})
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading Word {file_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_excel(file_path, keyword):
|
||||
try:
|
||||
# 根据文件扩展名选择合适的引擎
|
||||
if file_path.lower().endswith('.xls'):
|
||||
engine = 'xlrd'
|
||||
else:
|
||||
engine = 'openpyxl'
|
||||
excel_file = pd.ExcelFile(file_path, engine=engine)
|
||||
sheet_names = excel_file.sheet_names
|
||||
matches = []
|
||||
for sheet_name in sheet_names:
|
||||
df = excel_file.parse(sheet_name)
|
||||
for index, row in df.iterrows():
|
||||
for col, value in row.items():
|
||||
if pd.notna(value):
|
||||
value_str = str(value)
|
||||
if keyword in value_str:
|
||||
matches.append({
|
||||
'sheet': sheet_name,
|
||||
'row': index + 1,
|
||||
'column': col,
|
||||
'value': value_str
|
||||
})
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading Excel {file_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
# 添加文本文件搜索函数(适用于TXT、PHP、JS、HTML)
|
||||
def search_text(file_path, keyword):
|
||||
try:
|
||||
with open(file_path, 'r', encoding='utf-8', errors='ignore') as file:
|
||||
matches = []
|
||||
for line_num, line in enumerate(file, start=1):
|
||||
if keyword in line:
|
||||
matches.append({'line': line_num, 'value': line.strip()})
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading text file {file_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_zip(zip_path, keyword):
|
||||
try:
|
||||
with zipfile.ZipFile(zip_path, 'r') as zip_ref:
|
||||
matches = []
|
||||
for file_info in zip_ref.infolist():
|
||||
if stop_flag.is_set():
|
||||
break
|
||||
while pause_flag.is_set():
|
||||
time.sleep(0.1)
|
||||
file_name = file_info.filename
|
||||
# 添加对新文件类型的支持
|
||||
if file_name.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls', '.txt', '.php', '.js', '.html')):
|
||||
with zip_ref.open(file_name) as file:
|
||||
temp_file_path = f"temp_{file_name}"
|
||||
with open(temp_file_path, 'wb') as temp_file:
|
||||
temp_file.write(file.read())
|
||||
if file_name.lower().endswith('.pdf'):
|
||||
file_matches = search_pdf(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith('.docx'):
|
||||
file_matches = search_word(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith(('.xlsx', '.xls')):
|
||||
file_matches = search_excel(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith(('.txt', '.php', '.js', '.html')):
|
||||
file_matches = search_text(temp_file_path, keyword)
|
||||
if file_matches:
|
||||
matches.append((file_name, file_matches))
|
||||
os.remove(temp_file_path)
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading ZIP {zip_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_7z(seven_zip_path, keyword):
|
||||
try:
|
||||
with py7zr.SevenZipFile(seven_zip_path, mode='r') as archive:
|
||||
matches = []
|
||||
for file_info in archive.getnames():
|
||||
if stop_flag.is_set():
|
||||
break
|
||||
while pause_flag.is_set():
|
||||
time.sleep(0.1)
|
||||
# 添加对新文件类型的支持
|
||||
if file_info.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls', '.txt', '.php', '.js', '.html')):
|
||||
archive.extract(path='temp_extract', targets=[file_info])
|
||||
temp_file_path = os.path.join('temp_extract', file_info)
|
||||
if file_info.lower().endswith('.pdf'):
|
||||
file_matches = search_pdf(temp_file_path, keyword)
|
||||
elif file_info.lower().endswith('.docx'):
|
||||
file_matches = search_word(temp_file_path, keyword)
|
||||
elif file_info.lower().endswith(('.xlsx', '.xls')):
|
||||
file_matches = search_excel(temp_file_path, keyword)
|
||||
elif file_info.lower().endswith(('.txt', '.php', '.js', '.html')):
|
||||
file_matches = search_text(temp_file_path, keyword)
|
||||
if file_matches:
|
||||
matches.append((file_info, file_matches))
|
||||
os.remove(temp_file_path)
|
||||
import shutil
|
||||
shutil.rmtree('temp_extract', ignore_errors=True)
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading 7-Zip {seven_zip_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_rar(rar_path, keyword):
|
||||
try:
|
||||
rar = rarfile.RarFile(rar_path)
|
||||
matches = []
|
||||
for file_info in rar.infolist():
|
||||
if stop_flag.is_set():
|
||||
break
|
||||
while pause_flag.is_set():
|
||||
time.sleep(0.1)
|
||||
file_name = file_info.filename
|
||||
# 添加对新文件类型的支持
|
||||
if file_name.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls', '.txt', '.php', '.js', '.html')):
|
||||
rar.extract(file_info, path='temp_extract')
|
||||
temp_file_path = os.path.join('temp_extract', file_name)
|
||||
if file_name.lower().endswith('.pdf'):
|
||||
file_matches = search_pdf(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith('.docx'):
|
||||
file_matches = search_word(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith(('.xlsx', '.xls')):
|
||||
file_matches = search_excel(temp_file_path, keyword)
|
||||
elif file_name.lower().endswith(('.txt', '.php', '.js', '.html')):
|
||||
file_matches = search_text(temp_file_path, keyword)
|
||||
if file_matches:
|
||||
matches.append((file_name, file_matches))
|
||||
os.remove(temp_file_path)
|
||||
import shutil
|
||||
shutil.rmtree('temp_extract', ignore_errors=True)
|
||||
return matches
|
||||
except Exception as e:
|
||||
print(f"Error reading RAR {rar_path}: {e}")
|
||||
return []
|
||||
|
||||
|
||||
def search_folder(folder_path, keyword, progress_callback):
|
||||
results = {
|
||||
'pdf': [],
|
||||
'word': [],
|
||||
'excel': [],
|
||||
'zip': [],
|
||||
'7z': [],
|
||||
'rar': [],
|
||||
'txt': [], # 新增
|
||||
'php': [], # 新增
|
||||
'js': [], # 新增
|
||||
'html': [] # 新增
|
||||
}
|
||||
all_files = []
|
||||
for root, dirs, files in os.walk(folder_path):
|
||||
for file in files:
|
||||
# 添加对新文件类型的支持
|
||||
if file.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls', '.zip', '.7z', '.rar',
|
||||
'.txt', '.php', '.js', '.html')):
|
||||
all_files.append(os.path.join(root, file))
|
||||
|
||||
total_files = len(all_files)
|
||||
for i, file_path in enumerate(all_files):
|
||||
if stop_flag.is_set():
|
||||
break
|
||||
while pause_flag.is_set():
|
||||
time.sleep(0.1)
|
||||
if file_path.lower().endswith('.pdf'):
|
||||
matches = search_pdf(file_path, keyword)
|
||||
if matches:
|
||||
results['pdf'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.docx'):
|
||||
matches = search_word(file_path, keyword)
|
||||
if matches:
|
||||
results['word'].append((file_path, matches))
|
||||
elif file_path.lower().endswith(('.xlsx', '.xls')):
|
||||
matches = search_excel(file_path, keyword)
|
||||
if matches:
|
||||
results['excel'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.zip'):
|
||||
matches = search_zip(file_path, keyword)
|
||||
if matches:
|
||||
results['zip'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.7z'):
|
||||
matches = search_7z(file_path, keyword)
|
||||
if matches:
|
||||
results['7z'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.rar'):
|
||||
matches = search_rar(file_path, keyword)
|
||||
if matches:
|
||||
results['rar'].append((file_path, matches))
|
||||
# 添加新文件类型的处理
|
||||
elif file_path.lower().endswith('.txt'):
|
||||
matches = search_text(file_path, keyword)
|
||||
if matches:
|
||||
results['txt'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.php'):
|
||||
matches = search_text(file_path, keyword)
|
||||
if matches:
|
||||
results['php'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.js'):
|
||||
matches = search_text(file_path, keyword)
|
||||
if matches:
|
||||
results['js'].append((file_path, matches))
|
||||
elif file_path.lower().endswith('.html'):
|
||||
matches = search_text(file_path, keyword)
|
||||
if matches:
|
||||
results['html'].append((file_path, matches))
|
||||
|
||||
progress = (i + 1) / total_files * 100
|
||||
progress_callback(progress)
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def format_pdf_results(results, keyword):
|
||||
formatted = []
|
||||
for file_path, matches in results:
|
||||
formatted.append(f"【PDF搜索结果】")
|
||||
formatted.append(f"📄 <a href='{file_path}'>文件路径:{file_path}</a>")
|
||||
for i, match in enumerate(matches, start=1):
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'page': {match['page']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def format_word_results(results, keyword):
|
||||
formatted = []
|
||||
for file_path, matches in results:
|
||||
formatted.append(f"【Word搜索结果】")
|
||||
formatted.append(f"📄 <a href='{file_path}'>文件路径:{file_path}</a>")
|
||||
for i, match in enumerate(matches, start=1):
|
||||
if 'paragraph' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'paragraph': {match['paragraph']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'table' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'table': {match['table']}, 'row': {match['row']}, 'cell': {match['cell']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def format_excel_results(results, keyword):
|
||||
formatted = []
|
||||
for file_path, matches in results:
|
||||
formatted.append(f"【Excel搜索结果】")
|
||||
formatted.append(f"📄 <a href='{file_path}'>文件路径:{file_path}</a>")
|
||||
for i, match in enumerate(matches, start=1):
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'sheet': '{match['sheet']}', 'row': {match['row']}, 'column': '{match['column']}', 'value': '{highlight_keyword(str(match['value']), keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
# 添加文本类文件的结果格式化函数
|
||||
def format_text_results(results, keyword, file_type):
|
||||
formatted = []
|
||||
for file_path, matches in results:
|
||||
formatted.append(f"【{file_type}搜索结果】")
|
||||
formatted.append(f"📄 <a href='{file_path}'>文件路径:{file_path}</a>")
|
||||
for i, match in enumerate(matches, start=1):
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'line': {match['line']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def format_zip_results(results, keyword):
|
||||
formatted = []
|
||||
for zip_path, matches in results:
|
||||
formatted.append(f"【ZIP搜索结果】")
|
||||
formatted.append(f"📦 <a href='{zip_path}'>压缩包路径:{zip_path}</a>")
|
||||
for file_name, file_matches in matches:
|
||||
formatted.append(f" 📄 压缩包内文件:{file_name}")
|
||||
for i, match in enumerate(file_matches, start=1):
|
||||
if 'page' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'page': {match['page']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'paragraph' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'paragraph': {match['paragraph']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'sheet' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'sheet': '{match['sheet']}', 'row': {match['row']}, 'column': '{match['column']}', 'value': '{highlight_keyword(str(match['value']), keyword)}'}}")
|
||||
# 添加对文本类文件的支持
|
||||
elif 'line' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'line': {match['line']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def format_7z_results(results, keyword):
|
||||
formatted = []
|
||||
for seven_zip_path, matches in results:
|
||||
formatted.append(f"【7-Zip搜索结果】")
|
||||
formatted.append(f"📦 <a href='{seven_zip_path}'>压缩包路径:{seven_zip_path}</a>")
|
||||
for file_name, file_matches in matches:
|
||||
formatted.append(f" 📄 压缩包内文件:{file_name}")
|
||||
for i, match in enumerate(file_matches, start=1):
|
||||
if 'page' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'page': {match['page']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'paragraph' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'paragraph': {match['paragraph']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'sheet' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'sheet': '{match['sheet']}', 'row': {match['row']}, 'column': '{match['column']}', 'value': '{highlight_keyword(str(match['value']), keyword)}'}}")
|
||||
# 添加对文本类文件的支持
|
||||
elif 'line' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'line': {match['line']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def format_rar_results(results, keyword):
|
||||
formatted = []
|
||||
for rar_path, matches in results:
|
||||
formatted.append(f"【RAR搜索结果】")
|
||||
formatted.append(f"📦 <a href='{rar_path}'>压缩包路径:{rar_path}</a>")
|
||||
for file_name, file_matches in matches:
|
||||
formatted.append(f" 📄 压缩包内文件:{file_name}")
|
||||
for i, match in enumerate(file_matches, start=1):
|
||||
if 'page' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'page': {match['page']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'paragraph' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'paragraph': {match['paragraph']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
elif 'sheet' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'sheet': '{match['sheet']}', 'row': {match['row']}, 'column': '{match['column']}', 'value': '{highlight_keyword(str(match['value']), keyword)}'}}")
|
||||
# 添加对文本类文件的支持
|
||||
elif 'line' in match:
|
||||
formatted.append(
|
||||
f" 🔍 匹配{i}: {{'line': {match['line']}, 'value': '{highlight_keyword(match['value'], keyword)}'}}")
|
||||
formatted.append("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━")
|
||||
return '\n'.join(formatted)
|
||||
|
||||
|
||||
def highlight_keyword(text, keyword):
|
||||
parts = text.split(keyword)
|
||||
result = parts[0]
|
||||
for part in parts[1:]:
|
||||
result += f'{{{keyword}}}' + part
|
||||
return result
|
||||
|
||||
|
||||
def insert_highlighted_text(text_widget, text, keyword):
|
||||
index = '1.0'
|
||||
while True:
|
||||
pos = text_widget.search(f'{{{keyword}}}', index, tk.END)
|
||||
if not pos:
|
||||
break
|
||||
end_pos = f'{pos}+{len(keyword) + 2}c'
|
||||
text_widget.insert(pos, keyword, 'highlight')
|
||||
text_widget.delete(end_pos)
|
||||
index = end_pos
|
||||
|
||||
|
||||
def open_file(event):
|
||||
widget = event.widget
|
||||
index = widget.index(tk.CURRENT)
|
||||
url = widget.tag_names(index)[0]
|
||||
if url.startswith('http'):
|
||||
webbrowser.open(url)
|
||||
else:
|
||||
os.startfile(url)
|
||||
|
||||
|
||||
def select_folder():
|
||||
folder_path = filedialog.askdirectory()
|
||||
folder_entry.delete(0, tk.END)
|
||||
folder_entry.insert(0, folder_path)
|
||||
|
||||
|
||||
def update_progress(progress):
|
||||
progress_bar['value'] = progress
|
||||
if progress == 100:
|
||||
status_label.config(text="搜索完成")
|
||||
root.update_idletasks()
|
||||
|
||||
|
||||
def perform_search():
|
||||
global pause_flag, stop_flag
|
||||
pause_flag.clear()
|
||||
stop_flag.clear()
|
||||
status_label.config(text="")
|
||||
folder_path = folder_entry.get()
|
||||
keyword = keyword_entry.get()
|
||||
if not folder_path or not keyword:
|
||||
messagebox.showerror("错误", "请输入文件夹路径和关键字。")
|
||||
return
|
||||
search_thread = threading.Thread(target=search_and_display, args=(folder_path, keyword))
|
||||
search_thread.start()
|
||||
|
||||
|
||||
def search_and_display(folder_path, keyword):
|
||||
all_results = search_folder(folder_path, keyword, update_progress)
|
||||
pdf_results = format_pdf_results(all_results['pdf'], keyword)
|
||||
word_results = format_word_results(all_results['word'], keyword)
|
||||
excel_results = format_excel_results(all_results['excel'], keyword)
|
||||
zip_results = format_zip_results(all_results['zip'], keyword)
|
||||
seven_zip_results = format_7z_results(all_results['7z'], keyword)
|
||||
rar_results = format_rar_results(all_results['rar'], keyword)
|
||||
# 新增文本类文件结果处理
|
||||
txt_results = format_text_results(all_results['txt'], keyword, "TXT")
|
||||
php_results = format_text_results(all_results['php'], keyword, "PHP")
|
||||
js_results = format_text_results(all_results['js'], keyword, "JS")
|
||||
html_results = format_text_results(all_results['html'], keyword, "HTML")
|
||||
|
||||
# 更新原有标签页内容
|
||||
pdf_text.delete(1.0, tk.END)
|
||||
pdf_text.insert(tk.END, pdf_results)
|
||||
insert_highlighted_text(pdf_text, pdf_results, keyword)
|
||||
for tag in pdf_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
pdf_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
pdf_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
word_text.delete(1.0, tk.END)
|
||||
word_text.insert(tk.END, word_results)
|
||||
insert_highlighted_text(word_text, word_results, keyword)
|
||||
for tag in word_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
word_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
word_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
excel_text.delete(1.0, tk.END)
|
||||
excel_text.insert(tk.END, excel_results)
|
||||
insert_highlighted_text(excel_text, excel_results, keyword)
|
||||
for tag in excel_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
excel_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
excel_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
zip_text.delete(1.0, tk.END)
|
||||
zip_text.insert(tk.END, zip_results)
|
||||
insert_highlighted_text(zip_text, zip_results, keyword)
|
||||
for tag in zip_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
zip_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
zip_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
seven_zip_text.delete(1.0, tk.END)
|
||||
seven_zip_text.insert(tk.END, seven_zip_results)
|
||||
insert_highlighted_text(seven_zip_text, seven_zip_results, keyword)
|
||||
for tag in seven_zip_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
seven_zip_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
seven_zip_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
rar_text.delete(1.0, tk.END)
|
||||
rar_text.insert(tk.END, rar_results)
|
||||
insert_highlighted_text(rar_text, rar_results, keyword)
|
||||
for tag in rar_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
rar_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
rar_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
# 新增文本类文件标签页内容更新
|
||||
txt_text.delete(1.0, tk.END)
|
||||
txt_text.insert(tk.END, txt_results)
|
||||
insert_highlighted_text(txt_text, txt_results, keyword)
|
||||
for tag in txt_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
txt_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
txt_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
php_text.delete(1.0, tk.END)
|
||||
php_text.insert(tk.END, php_results)
|
||||
insert_highlighted_text(php_text, php_results, keyword)
|
||||
for tag in php_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
php_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
php_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
js_text.delete(1.0, tk.END)
|
||||
js_text.insert(tk.END, js_results)
|
||||
insert_highlighted_text(js_text, js_results, keyword)
|
||||
for tag in js_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
js_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
js_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
html_text.delete(1.0, tk.END)
|
||||
html_text.insert(tk.END, html_results)
|
||||
insert_highlighted_text(html_text, html_results, keyword)
|
||||
for tag in html_text.tag_names():
|
||||
if tag.startswith('http') or os.path.exists(tag):
|
||||
html_text.tag_configure(tag, foreground='blue', underline=True)
|
||||
html_text.tag_bind(tag, '<Button-1>', open_file)
|
||||
|
||||
|
||||
def pause_search():
|
||||
if pause_flag.is_set():
|
||||
pause_flag.clear()
|
||||
pause_button.config(text="暂停")
|
||||
else:
|
||||
pause_flag.set()
|
||||
pause_button.config(text="继续")
|
||||
|
||||
|
||||
def stop_search():
|
||||
global stop_flag
|
||||
stop_flag.set()
|
||||
progress_bar['value'] = 0
|
||||
status_label.config(text="")
|
||||
|
||||
|
||||
# 创建主窗口
|
||||
root = tk.Tk()
|
||||
root.title("文件搜索工具")
|
||||
|
||||
# 设置字体大小
|
||||
font_size = 14
|
||||
|
||||
# 文件夹选择部分
|
||||
folder_label = tk.Label(root, text="选择文件夹:", font=("Arial", font_size))
|
||||
folder_label.pack(pady=5)
|
||||
|
||||
folder_entry = tk.Entry(root, width=50, font=("Arial", font_size))
|
||||
folder_entry.pack(pady=5)
|
||||
|
||||
select_button = tk.Button(root, text="选择文件夹", command=select_folder, font=("Arial", font_size))
|
||||
select_button.pack(pady=5)
|
||||
|
||||
# 关键字输入部分
|
||||
keyword_label = tk.Label(root, text="输入关键字:", font=("Arial", font_size))
|
||||
keyword_label.pack(pady=5)
|
||||
|
||||
keyword_entry = tk.Entry(root, width=50, font=("Arial", font_size))
|
||||
keyword_entry.pack(pady=5)
|
||||
|
||||
# 搜索、暂停和停止按钮部分
|
||||
button_frame = tk.Frame(root)
|
||||
button_frame.pack(pady=5)
|
||||
|
||||
search_button = tk.Button(button_frame, text="开始搜索", command=perform_search, font=("Arial", font_size))
|
||||
search_button.pack(side=tk.LEFT, padx=5)
|
||||
|
||||
pause_button = tk.Button(button_frame, text="暂停", command=pause_search, font=("Arial", font_size))
|
||||
pause_button.pack(side=tk.LEFT, padx=5)
|
||||
|
||||
stop_button = tk.Button(button_frame, text="停止", command=stop_search, font=("Arial", font_size))
|
||||
stop_button.pack(side=tk.LEFT, padx=5)
|
||||
|
||||
# 进度条和状态标签
|
||||
progress_frame = tk.Frame(root)
|
||||
progress_frame.pack(pady=10)
|
||||
|
||||
progress_bar = ttk.Progressbar(progress_frame, orient="horizontal", length=300, mode="determinate")
|
||||
progress_bar.pack(side=tk.LEFT)
|
||||
|
||||
status_label = tk.Label(progress_frame, text="", font=("Arial", font_size))
|
||||
status_label.pack(side=tk.LEFT, padx=10)
|
||||
|
||||
# 创建 Notebook 组件
|
||||
notebook = ttk.Notebook(root)
|
||||
notebook.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
|
||||
# 创建原有标签页
|
||||
word_tab = tk.Frame(notebook)
|
||||
notebook.add(word_tab, text="Word 结果")
|
||||
word_text = tk.Text(word_tab, width=60, height=20, font=("Arial", font_size))
|
||||
word_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
word_text.tag_config('highlight', foreground='red')
|
||||
|
||||
excel_tab = tk.Frame(notebook)
|
||||
notebook.add(excel_tab, text="Excel 结果")
|
||||
excel_text = tk.Text(excel_tab, width=60, height=20, font=("Arial", font_size))
|
||||
excel_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
excel_text.tag_config('highlight', foreground='red')
|
||||
|
||||
pdf_tab = tk.Frame(notebook)
|
||||
notebook.add(pdf_tab, text="PDF 结果")
|
||||
pdf_text = tk.Text(pdf_tab, width=60, height=20, font=("Arial", font_size))
|
||||
pdf_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
pdf_text.tag_config('highlight', foreground='red')
|
||||
|
||||
zip_tab = tk.Frame(notebook)
|
||||
notebook.add(zip_tab, text="ZIP 结果")
|
||||
zip_text = tk.Text(zip_tab, width=60, height=20, font=("Arial", font_size))
|
||||
zip_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
zip_text.tag_config('highlight', foreground='red')
|
||||
|
||||
seven_zip_tab = tk.Frame(notebook)
|
||||
notebook.add(seven_zip_tab, text="7-Zip 结果")
|
||||
seven_zip_text = tk.Text(seven_zip_tab, width=60, height=20, font=("Arial", font_size))
|
||||
seven_zip_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
seven_zip_text.tag_config('highlight', foreground='red')
|
||||
|
||||
rar_tab = tk.Frame(notebook)
|
||||
notebook.add(rar_tab, text="RAR 结果")
|
||||
rar_text = tk.Text(rar_tab, width=60, height=20, font=("Arial", font_size))
|
||||
rar_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
rar_text.tag_config('highlight', foreground='red')
|
||||
|
||||
# 添加新文件类型的标签页
|
||||
txt_tab = tk.Frame(notebook)
|
||||
notebook.add(txt_tab, text="TXT 结果")
|
||||
txt_text = tk.Text(txt_tab, width=60, height=20, font=("Arial", font_size))
|
||||
txt_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
txt_text.tag_config('highlight', foreground='red')
|
||||
|
||||
php_tab = tk.Frame(notebook)
|
||||
notebook.add(php_tab, text="PHP 结果")
|
||||
php_text = tk.Text(php_tab, width=60, height=20, font=("Arial", font_size))
|
||||
php_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
php_text.tag_config('highlight', foreground='red')
|
||||
|
||||
js_tab = tk.Frame(notebook)
|
||||
notebook.add(js_tab, text="JS 结果")
|
||||
js_text = tk.Text(js_tab, width=60, height=20, font=("Arial", font_size))
|
||||
js_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
js_text.tag_config('highlight', foreground='red')
|
||||
|
||||
html_tab = tk.Frame(notebook)
|
||||
notebook.add(html_tab, text="HTML 结果")
|
||||
html_text = tk.Text(html_tab, width=60, height=20, font=("Arial", font_size))
|
||||
html_text.pack(pady=10, fill=tk.BOTH, expand=True)
|
||||
html_text.tag_config('highlight', foreground='red')
|
||||
|
||||
# 运行主循环
|
||||
root.mainloop()
|
||||
Reference in New Issue
Block a user