如何使用python从目录中的所有文本文件中查找特定单词

时间:2017-03-31 14:41:54

标签: python

我有文字文件。我想打开那个文本文件并搜索一个名为“OPR”的单词 在Final.txt文件中出现的单词写入该特定字符串示例代码的3行 如下所示

text1="Some decoders allow you to manipulate the image reading"
text2="file.This can often be used to speed up decoding when creating" 
text3="when speed is usually more important than quality  printing"
text4="monochrome laser printer when only a greyscale"
text4="Note that the resulting image may not exactly match the requested"
text5="mode and size. To make sure that the image is not larger"
text6="given size, use the thumbnail method instead."


output_file=open("Final.txt","a")
output_file.write(text1)
output_file.write(text2)
output_file.write(text3)
output_file.write(text4)
output_file.write(text5)
output_file.write(text6)
output_file.close()

import collections
import itertools
import sys
with open('output\\Final.txt') as f:
  for line in f:
    if 'used' in line:
        print("OPR")
        sys.stdout.write(line)
        sys.stdout.writelines(itertools.islice(f, 4))

我的疑问是我在一些目录中有3个名为Finaltxt.1,Finaltxt.2,Finaltxt.3的文本文件 我如何检查所有三个文本文件的“used”单词并写入3行文本 我在上面的代码上做了

1 个答案:

答案 0 :(得分:0)

查看下面的代码,因为我认为它符合您的目标:

output_file=open("file.txt","w")
output_file.write("file: lineNo1 \n")
output_file.write("file: lineNo2 used \n")
output_file.write("file: lineNo3 \n")
output_file.write("file: lineNo4 used \n")
output_file.write("file: lineNo5 \n")
output_file.write("file: lineNo6 \n")
output_file.close() 

output_file=open("file1.txt","w")
output_file.write("file1: lineNo1 \n")
output_file.write("file1: lineNo2 \n")
output_file.write("file1: lineNo3 \n")
output_file.write("file1: lineNo4 used \n")
output_file.write("file1: lineNo5 \n")
output_file.write("file1: lineNo6 \n")
output_file.close()

output_file=open("file2.txt","w")
output_file.write("file2: lineNo1 \n")
output_file.write("file2: lineNo2 \n")
output_file.write("file2: lineNo3 \n")
output_file.write("file2: lineNo4 \n")
output_file.write("file2: lineNo5 \n")
output_file.write("file2: lineNo6 used \n")
output_file.close()

import collections
import itertools
import sys
with open('file.txt') as f, open('file1.txt') as f1, open('file2.txt') as f2 :
  fTXT, f1TXT, f2TXT = f.readlines(), f1.readlines(), f2.readlines()   
  for lineNo in range(0, min(len(fTXT), len(f1TXT), len(f2TXT)) ):
      if 'used' in fTXT[lineNo] or 'used' in f1TXT[lineNo] or 'used' in f2TXT[lineNo]:
          print("OPR")
          sys.stdout.write("###" + fTXT[lineNo] + "###" + f1TXT[lineNo] + "###" + f2TXT[lineNo])

输出:

OPR
###file: lineNo2 used 
###file1: lineNo2 
###file2: lineNo2 
OPR
###file: lineNo4 used 
###file1: lineNo4 used 
###file2: lineNo4 
OPR
###file: lineNo6 
###file1: lineNo6 
###file2: lineNo6 used