|
|
10鱼币
题目:http://bbs.fishc.com/forum.php?m ... peid%26typeid%3D398
我开始写的代码是:
- import os
- def search_keyword(keyword,answer):
- count = 0
- list1 = []
- n = 0
- for each_file in os.listdir(os.curdir):
- if os.path.splitext(each_file)[-1] == '.txt':
- f = open(os.getcwd() + os.sep + each_file)
- for each_line in f:
- count += 1
- if each_line.count(keyword) != 0:
- print('============================================================')
- print('在文件【%s】中找到关键字【%s】'% (os.getcwd() + os.sep + each_file,keyword))
- if answer == 'yes':
- while 1:
- n = each_line.find(keyword,n)
- list1.append(n + 1)
- n += 1
- if each_line.find(keyword,n) == -1:
- break
- print('关键字出现在第%s行,第%s个位置。' % (str(count),list1))
- list1 = []
- n = 0
- count = 0
- f.close()
- if os.path.isdir(each_file):
- os.chdir(each_file)
- search_keyword(keyword,answer)
- os.chdir(os.pardir)
- keyword = input('请将该脚本放入待查找的文件夹内,请输入关键字:')
- answer = input('请问是否需要打印关键字【%s】在文件中的具体位置(yes/no):' % keyword)
- search_keyword(keyword,answer)
复制代码
文件是:
输入 丁 和 yes
得到的结果为:
后来我改代码为:
- import os
- def search_keyword(keyword,answer):
- count = 0
- list1 = []
- n = 0
- for each_file in os.listdir(os.curdir):
- if os.path.splitext(each_file)[-1] == '.txt':
- f = open(os.getcwd() + os.sep + each_file)
- print_keyword(f,keyword,each_file)
- if answer == 'yes':
- for each_line in f:
- count += 1
- while 1:
- n = each_line.find(keyword,n)
- list1.append(n + 1)
- n += 1
- if each_line.find(keyword,n) == -1:
- break
- print('关键字出现在第%s行,第%s个位置。' % (str(count),list1))
- list1 = []
- n = 0
- count = 0
- f.close()
- if os.path.isdir(each_file):
- os.chdir(each_file)
- search_keyword(keyword,answer)
- os.chdir(os.pardir)
- def print_keyword(f,keyword,each_file):
- for h in f:
- if h.count(keyword) != 0:
- print('============================================================')
- print('在文件【%s】中找到关键字【%s】'% (os.getcwd() + os.sep + each_file,keyword))
- return
-
- keyword = input('请将该脚本放入待查找的文件夹内,请输入关键字:')
- answer = input('请问是否需要打印关键字【%s】在文件中的具体位置(yes/no):' % keyword)
- search_keyword(keyword,answer)
复制代码
结果为:
求大神们帮我看看,十分感谢 |
最佳答案
查看完整内容
1、print_keyword(f,keyword,each_file) 调用打印函数的时候,指针已经跳到有关键字的行。所以while循环查找关键字是从有关键字的下一行开始查找。 -----行数错误的原因
2、while 循环:先查找再判断是不对的。如果查找的行没有该关键字,会返回-1 ,然后再判断有没关键字。应该把if语句放到while循环的最前面----------取index错误的原因
n = each_line.find(keyword,n)
print (n)
list1.append(n + 1)
3、print('关键字 ...
|