鱼C论坛

 找回密码
 立即注册
查看: 2137|回复: 0

30课的课后作业最后一题

[复制链接]
发表于 2016-7-2 18:10:52 | 显示全部楼层 |阅读模式

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

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

x
import os


key = input('请输入需要查找的关键字:')

choice = input('请问需要打印关键字的位置吗:')

def print_key(key,choice):
    for each in os.walk(os.getcwd()):
        for i in each[2]:
            if os.path.splitext(i)[1] == '.txt':
                print(each[0])
                file = os.path.join(each[0],i)
                print(each[0])
                f= open(file)
                count = 0
                key_dict={}
                for each in f:
                    count +=1
                    if key in each:
                        begin = each.find(key)
                        pos = []
                        while begin != -1:
                            pos.append(begin + 1)
                            begin = each.find(key,begin + 1)
                        key_dict[count] = pos
                if key_dict:
                    print('===\n在文件【%s】中找到关键字【%s】' % (file,key))
                if choice in ['yes','YES','Yes']:
                    keys = key_dict.keys()
                    keys = sorted(keys)
                    for each_key in keys:
                        print('关键字出现在第%s行,第%s个位置'% (each_key,str(key_dict[each_key])))
print_key(key,choice)  

看完答案自己凭记忆由打了一遍,运行时会报错,但自己找不出错误来错误提示以及运行的结果
请输入需要查找的关键字:1
请问需要打印关键字的位置吗:yes
D:\Python32\test
D:\Python32\test
===
在文件【D:\Python32\test\1.txt】中找到关键字【1】
关键字出现在第1行,第[1, 2, 3, 19, 23]个位置
关键字出现在第2行,第[12]个位置
关键字出现在第4行,第[1, 4, 7, 10]个位置
关键字出现在第5行,第[1, 4]个位置
关键字出现在第7行,第[1, 4]个位置
关键字出现在第8行,第[1, 4]个位置
关键字出现在第9行,第[1, 4]个位置
1
1
Traceback (most recent call last):
  File "D:\Python32\test\练习2.py", line 34, in <module>
    print_key(key,choice)
  File "D:\Python32\test\练习2.py", line 15, in print_key
    f= open(file)
IOError: [Errno 2] No such file or directory: '1\\12.txt'
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2026-2-21 13:03

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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