# -*- coding: utf-8 -*-
python列表的索引。import sys
reload(sys)
python遍歷目錄?sys.setdefaultencoding("utf-8")
import os
def print_pos(key_dict):
keys = key_dict.keys()
keys = sorted(keys) # 由于字典是無序的,我們這里對行數進行排序
for each_key in keys:
print("關鍵字出現在第 %s 行,第 %s 個位置。" % (each_key, str(key_dict[each_key])))
def pos_in_line(line, key):
pos = []
begin = line.find(key)
while begin != -1:
pos.append(begin + 1) # 用戶的角度是從1開始數
begin = line.find(key, begin + 1) # 從下一個位置繼續查找
return pos
def search_in_file(file_name, key):
f = open(file_name,"r")
count = 0 # 記錄行數
key_dict = dict() # 字典,用戶存放key所在具體行數對應具體位置
for each_line in f:
count += 1
if key in each_line:
pos = pos_in_line(each_line, key) # key在每行對應的位置
key_dict[count] = pos
f.close()
return key_dict
def search_files(key, detail):
all_files = os.walk(os.getcwd())
txt_files = []
for i in all_files:
for each_file in i[2]:
if os.path.splitext(each_file)[1] == ".txt": # 根據后綴判斷是否文本文件
each_file = os.path.join(i[0], each_file)
txt_files.append(each_file)
for each_txt_file in txt_files:
key_dict = search_in_file(each_txt_file, key)
if key_dict:
print "================================================================"
print "在文件【%s】中找到關鍵字【%s】" % (each_txt_file, key)
if detail in ["YES", "Yes", "yes"]:
print_pos(key_dict)
key = raw_input("請將該腳本放于待查找的文件夾內,請輸入關鍵字:")
detail = raw_input("請問是否需要打印關鍵字【%s】在文件中的具體位置(YES/NO):" % key)
search_files(key, detail)
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态