鱼C论坛

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

第三十课最后一题

[复制链接]
发表于 2017-2-13 19:21:09 | 显示全部楼层 |阅读模式
5鱼币
import os
def print_pos(dict1):
    keys=dict1.keys()
    keys=sorted(keys)
    for each in keys:
        print('关键字出现在%s行,%s个位置'% (each,str(dict1[each])))
        
def line_pos(each_line,key):
    pos=[]
    begin=each_line.find(key)
    while begin != -1:
        pos.append(begin+1)
        begin=each_line.find(key,begin+1)
    return pos
        
def file_line(each_file1,key):
    f=open(each_file1)
    count=0
    dict1=dict()
    for each_line in f:
        count+=1
        if key in each_line:
            pos=line_pos(each_line,key)
            dict1[count]=pos
    f.close()
    return dict1

def search_file(start_dir,key):
    os.chdir(start_dir)
    list_file=[]
    all_files=os.walk(os.curdir)
   
    for each_file in all_files:
        for i in each_file[2]:
            if '.txt' in i:
                temp1=os.path.join(each_file[0],i)
                list_file.append(temp1)
               
    for each_file1 in list_file:
        a=file_line(each_file1,key)
        if a:
            print('===============================================================')
            print('在文件%s中,找到关键词%s'% (each_file1,key))
            print_pos(dict1)         #是这里出错了吗?
        
start_dir=input('请输入要查找的目录:')
key=input('请输入要查找的关键词:')
search_file(start_dir,key)

为什么返回
Traceback (most recent call last):
  File "C:/Users/杜一鸣/Desktop/temp.py", line 49, in <module>
    search_file(start_dir,key)
  File "C:/Users/杜一鸣/Desktop/temp.py", line 44, in search_file
    print(dict1)
NameError: global name 'dict1' is not defined
请大神们帮看看,哪里错了,我分明定义过dict1了,谢谢!

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-2-13 19:29:21 | 显示全部楼层

图片

本帖最后由 yamal 于 2017-2-13 19:30 编辑

未命名_副本.jpg
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2017-2-13 20:20:12 | 显示全部楼层
本帖最后由 yamal 于 2017-2-13 20:21 编辑


我知道哪里错了,哈哈,柳暗花明

a换成dict1就行了
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

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

本版积分规则

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

GMT+8, 2024-4-26 18:21

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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