python列表的索引,python 小程序搜索排名-用python2.7.9 寫個小程序搜索某個目錄下行有某關鍵字

 2023-11-19 阅读 28 评论 0

摘要:# -*- 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) # 由于字典是無序的,我們這里對行數進行排序

# -*- 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)

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/182747.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息