【问题标题】:searching a word in list of files(current directory) and returning all the files containg the word python在文件列表(当前目录)中搜索一个单词并返回所有包含单词 python 的文件
【发布时间】:2017-11-20 06:58:48
【问题描述】:
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

谁能告诉我哪里出错了?

【问题讨论】:

  • elif search in words:
  • 如果您使用search in words,则无需将文件内容拆分为行。
  • if search in open(files).read().lower():
  • 好的,我是新手,我有一个非常大的文件,比如 12 GB,我不想将所有文件都加载到内存中。一行一行就行了。

标签: python python-3.x search


【解决方案1】:
#!/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)

【讨论】:

  • 您好,我对 lambda 函数一无所知,您能写下基本的或解释一下吗?
  • @ShikharSaxena 我添加了基本版本。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-03
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2019-02-28
  • 2016-08-29
相关资源
最近更新 更多