阿摩線上測驗 登入

申論題資訊

試卷:97年 - 097年身心障礙人員4等_資訊處理#37700
科目:程式設計
年份:97年
排序:0

申論題內容

一、請寫一段程式,其可對一部電腦的儲存設備內所儲存之所有文字檔案(text file)進 行關鍵字搜尋(keywords search)。(40 分) ⑴可以接受使用者輸入中文、英文或中英夾雜之關鍵字進行搜尋。 ⑵須將所搜尋到之檔案名稱(file name)及包含該關鍵字前、後幾個字之段落 (segment),記錄起來。 ⑶須能統計並顯示出總共搜尋到多少檔案、多少段落。

詳解 (共 1 筆)

詳解 提供者:hchungw
接受使用者輸入的關鍵字(支持中文、英文或中英夾雜)。
遍歷指定目錄下的所有文字檔案,對每個檔案進行關鍵字搜尋。
對於包含關鍵字的檔案,記錄檔案名稱和包含關鍵字的文本段落。
統計並顯示搜尋到的檔案數量和段落數量。
python
Copy code
import os
def find_files_with_keyword(directory, keyword):
    file_count = 0
    segment_count = 0
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.txt'):  # 假設只搜尋.txt結尾的文件
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    contents = f.readlines()
                    matched_segments = [line.strip() for line in contents if keyword in line]
                    if matched_segments:
                        file_count += 1
                        segment_count += len(matched_segments)
                        print(f"檔案: {file_path}")
                        for segment in matched_segments:
                            print(f"段落: {segment}")
    return file_count, segment_count
# 使用者輸入關鍵字
keyword = input("請輸入要搜尋的關鍵字:")
directory = input("請輸入要搜尋的目錄路徑:")
# 執行搜尋
file_count, segment_count = find_files_with_keyword(directory, keyword)
# 顯示結果
print(f"\n總共搜尋到 {file_count} 個檔案,包含 {segment_count} 個包含關鍵字的段落。")
程式說明:
這段程式會遍歷使用者指定目錄下的所有.txt檔案。
對於每一個文檔,程式讀取其內容,檢查是否包含使用者指定的關鍵字。
如果一個文檔包含關鍵字,程式會輸出這個文檔的路徑和所有包含關鍵字的文本行。
最後,程式統計並顯示搜尋到的檔案數量和包含關鍵字的文本行數量。