鱼C论坛

 找回密码
 立即注册
查看: 3934|回复: 4

小甲鱼Python 第30讲课后习题看不懂

[复制链接]
发表于 2016-9-16 15:16:23 | 显示全部楼层 |阅读模式

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

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

x
小甲鱼,30讲课后习题最后一题调用太复杂看不懂
  1. import os                           #读取os文件

  2. def print_pos(key_dict):            #定义函数
  3.     keys = key_dict.keys()          #建立关键字空字典
  4.     keys = sorted(keys)             #把字典的键排序并生成列表
  5.     for each_key in keys:           #遍历所有的键
  6.         print('关键字出现在第 %s 行,第 %s 个位置。' % (each_key, str(key_dict[each_key])))
  7. #输出文本


  8. def pos_in_line(line, key):         #定义函数
  9.     pos = []                        #建立空列表
  10.     begin = line.find(key)          #每行找到关键词
  11.     while begin != -1:              #当没到最后一行时
  12.         pos.append(begin + 1)       #用户的角度是从1开始数
  13.         begin = line.find(key, begin+1)     #从下一个位置继续查找,begin+1表示新的开始

  14.     return pos                      #返回列表


  15. def search_in_file(file_name, key): #搜索文件中的关键字
  16.     f = open(file_name)             #打开指定的文件
  17.     count = 0                       # 记录行数
  18.     key_dict = dict()              # 字典,用户存放key所在具体行数对应具体位置
  19.    
  20.     for each_line in f:            #逐行提取
  21.         count += 1                 #计数加一
  22.         if key in each_line:       #如果含有关键词
  23.             pos = pos_in_line(each_line, key) # key在每行对应的位置
  24.             key_dict[count] = pos  #写入字典
  25.    
  26.     f.close()                       #关闭文件
  27.     return key_dict                 #返回字典


  28. def search_files(key, detail):      #定义函数
  29.     all_files = os.walk(os.getcwd())#遍历工作目录
  30.     txt_files = []                  #建立空的列表

  31.     for i in all_files:             #遍历所有文件
  32.         for each_file in i[2]:      #
  33.             if os.path.splitext(each_file)[1] == '.txt': # 根据后缀判断是否文本文件
  34.                 each_file = os.path.join(i[0], each_file)#合并路径
  35.                 txt_files.append(each_file)#列表增加文件名

  36.     for each_txt_file in txt_files: #按文件列表搜索
  37.         key_dict = search_in_file(each_txt_file, key) #调用函数
  38.         if key_dict:
  39.             print('================================================================')
  40.             print('在文件【%s】中找到关键字【%s】' % (each_txt_file, key))
  41.             if detail in ['YES', 'Yes', 'yes']:
  42.                 print_pos(key_dict)


  43. key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
  44. detail = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
  45. search_files(key, detail)

复制代码

费劲了好久加了注释,可是发现第一个函数全程没有被调用过,而且运行报错。。。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2016-9-16 15:18:09 | 显示全部楼层
报错如下:
  1. 请将该脚本放于待查找的文件夹内,请输入关键字:从明天起
  2. 请问是否需要打印关键字【从明天起】在文件中的具体位置(YES/NO):yes
  3. Traceback (most recent call last):
  4.   File "C:/Users/think/AppData/Local/Programs/Python/Python35-32/1.py", line 57, in <module>
  5.     search_files(key, detail)
  6.   File "C:/Users/think/AppData/Local/Programs/Python/Python35-32/1.py", line 47, in search_files
  7.     key_dict = search_in_file(each_txt_file, key) #调用函数
  8.   File "C:/Users/think/AppData/Local/Programs/Python/Python35-32/1.py", line 26, in search_in_file
  9.     for each_line in f:            #逐行提取
  10. UnicodeDecodeError: 'gbk' codec can't decode byte 0x99 in position 261: illegal multibyte sequence
复制代码

而且感觉逻辑上怪怪的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2016-9-16 15:21:01 | 显示全部楼层
还有41行看不懂
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-8 17:28:19 | 显示全部楼层
同样是遇到运行出错。而且搞不懂第二个函数line在哪儿被赋值了
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2018-1-18 14:12:11 | 显示全部楼层
本帖最后由 keydnal_aaron 于 2018-1-18 14:17 编辑

这个测试的文本里面是英文字符串,如果环境不同,注意下文本内容的编码方式,我的编程环境是centos7+python3.6.4

from os import walk,getcwd
from os.path import join

def search_file():
    '''
    查找当前目录底下的所有文件!
    return返回的结果为列表:‘/路径/文件.txt’
    '''
    file_list=[]
    for each_dir_file in walk(getcwd()):
        if each_dir_file[2] != []:
            for each_file in each_dir_file[2]:
                if each_file[-4:] == '.txt':
                    temppath=join(each_dir_file[0],each_file)
                    file_list.append(temppath)
    return file_list

def chazhao(filename,zfc):
    '''
    传入两个参数,文件名,要查找字符串
    查找匹配字符串的行
    生成结果以字典形式返回
    如果文件没有匹配字符串的行,返回空字典
    :param filename:
    :param zfc:
    :return:
    '''
    count1 = 0
    dict_line_weizhi = {}
    file = open(filename)
    for each_line in file:
        count1 += 1
        if zfc in each_line:
            weizhi=[]
            begin_zfc = each_line.find(zfc)
            while begin_zfc != -1:
                weizhi.append(begin_zfc)
                begin_zfc = each_line.find(zfc, begin_zfc + 1)
            dict_line_weizhi.setdefault(count1,weizhi)
        else:
            dict_line_weizhi={}
    file.close()
    return dict_line_weizhi

def zfc_line_weizhi(zfc,daying):
    '''
    接收用户输入需要查找的字符串zfc
    接收用户输入是否确认查询daying
    确认查询,返回查询结果
    确认不查询,退出程序
    :param zfc:
    :param daying:
    :return:
    '''
    if (daying == 'YES') or (daying == 'yes') or (daying == 'Yes'):
        file_list = search_file()
        for each_file in file_list:
            result = chazhao(each_file, zfc)
            if result != {}:
                print('在文件' + '[' + each_file + ']' + "中找到关键字" + '[' + zfc + ']')
                for each_key in result.keys():
                    print('关键字出现在第' + str(each_key) + '行,第' + str(result[each_key]) + '个位置!')
    else:
        print('退出查询!')


if __name__ =='__main__':
    zfc = input('请将该代码放于待查找的文件夹内,请输入关键字:').strip()
    daying = input('请问是否打印关键字' + zfc + '在文件中的具体位置(YES/NO):').strip()
    zfc_line_weizhi(zfc,daying)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-7-12 20:06

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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