鱼C论坛

 找回密码
 立即注册
查看: 2596|回复: 2

030讲第四题

[复制链接]
发表于 2016-4-21 21:03:35 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
无标题.png

import os
import os.path

def key_search(key):
        
    file_listdir = os.listdir(os.curdir)

    for each in file_listdir:
        if os.path.isfile(each) and each.split('.')[1] == 'txt':
            f = open(each)
            pos = []
            dict1 = dict()
            count = 0
            for each_line in f:
                count += 1
                if key in each_line:
                    begin  = each_line.find(key)
                    while begin != -1:
                        pos.append(begin + 1)
                        begin = each_line.find(key,begin + 1)
                    dict1.setdefault(count,pos)
        print('在文件【%s\\%s】中找到关键字【%s】'%(os.getcwd(),each,key))
        print('关键字出现在第%d行,第',dict1[count],'个位置')

        elif os.path.isdir(each):
            os.chdir(each)
            key_search(key)
            os.chdir('..')
                     
                    
                     

key = input('请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(yes/no):'%key)
key_search(key)


代码不能运行!!!!!!

无标题11.png


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2016-4-21 21:30:26 | 显示全部楼层
两行print要再缩进,另第二个print有错误
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-4-21 22:20:33 | 显示全部楼层
冬雪雪冬 发表于 2016-4-21 21:30
两行print要再缩进,另第二个print有错误

import os
import os.path

def key_search(key,detail):
        
    file_listdir = os.listdir(os.curdir)

    for each in file_listdir:
        if os.path.isfile(each) and each.split('.')[1] == 'txt':
            f = open(each)
            dict1 = dict()
            count = 0
            for each_line in f:
                count += 1
                if key in each_line:
                    pos = []
                    begin  = each_line.find(key)
                    while begin != -1:
                        pos.append(begin + 1)
                        begin = each_line.find(key,begin + 1)
                    dict1.setdefault(count,pos)
                    
            if dict1 != {}:
                print('\n在文件【%s\\%s】中找到关键字【%s】\n'%(os.getcwd(),each,key))
                if detail == 'yes':
                    for each in dict1.keys():
                        print('关键字出现在第%d行'%each,'第',dict1[each],'个位置\n')
                        

        elif os.path.isdir(each):
            os.chdir(each)
            key_search(key,detail)
            os.chdir('..')
                     
                    
                     

key = input('请输入关键字:')
detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(yes/no):'%key)
key_search(key,detail)


谢谢,已经解决了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-20 18:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表