搜索文件列表中的单词(当前目录)并返回包含单词python

时间:2017-11-20 06:58:48

标签: python python-3.x search

import os, sys
text = [file_search for file_search in os.listdir() if file_search.endswith('.txt') or file_search.endswith('.py')]
search = input()
print (text)
for files in text:
    lines_list = open(files).read().lower().splitlines()
    bool1 = False
    for words in lines_list:
        if bool1 == True:
            break
        elif words == search:
            print (files)
            bool1 = True
        else:
            bool1 = False

有人可以告诉我哪里出错了吗?

1 个答案:

答案 0 :(得分:0)

#!/usrbin/python3
# 2017.11.20 15:31:09 CST
import os, sys
ext = ".txt"
fnames = [fname for fname in os.listdir() if fname.endswith(ext)]
word = input("Input the search word: ") 
res1 = list(filter(lambda fname: word in open(fname).read(), fnames))
res2 = list(filter(lambda fname: word.lower() in open(fname).read().lower(), fnames))
print("result1:", res1)
print("result2:", res2)

## 2017.11.20 18:54:10 CST
## The basic version
res = []
for fname in fnames:
    #if word in open(fname).read():
    if word.lower() in open(fname).read().lower():
        res.append(fname)

print("result:", res)