2016-04-27 77 views
1

对于我的代码如下,我想打印出一个完整的句子,其中出现了我的单词列表中的某些单词,并且它会将每个特定单词下面的单词打印为一个。 txt文件。我在终端上成功地实现了这一点,但我真的很努力地把它变成一个.txt文件。目前我似乎只能打印出.txt中的字数,但句子仍在打印到终端,有人知道我可能会出错吗?对不起,我缺乏知识的初学者学习python。由于如何打印出一个.txt

import re, os 

pathWordLists = "E:\\Python\WordLists" 

searchfilesLists = os.listdir(pathWordLists) 

pathWordbooks = "E:\\Python\Books" 

searchfilesbooks = os.listdir(pathWordBooks) 

lush = open("WorkWork.txt", "w") 


def searchDocs(word): 

    for document in searchfilesbooks: 
     file = os.path.join(pathWordbooks, document) 
     text = open(file, "r") 
     hit_count = 0 
     for line in text: 
      if re.findall(word, line): 
       hit_count = hit_count +1 
       print(document + " |" + line, end="") 
     print(document + " => " + word + "=> "+ str(hit_count), file=lush) 
     text.close() 
    lush.flush() 
    return 

def searchWord(): 

    for document in searchfilesLists: 
     file = os.path.join(pathWordLists, document) 
     text = open(file, "r") 
     for line in text: 
      #print(line) 
      searchDocs(line.strip()) 
     text.close() 
    print("Finish") 

searchWord() 

回答

1

如果你打印句子print(document + " |" + line, end="")你忘了file参数。添加它应该可以解决问题:

print(document + " |" + line, end="", file=lush) 
+0

我已经将其添加到这两个 打印(文档+ “|” +线,结束= “”,文件=茂盛) 和 打印(文档+“=> “+ word +”=>“+ str(hit_count),file = lush) 它现在完美地将它们打印到.txt中,但由于某种原因它说'New Text Document.txt =>'在这附近。 谢谢你的帮助 – Gurnsie

+0

为了回答我需要知道你正在扫描的目录的内容和预期的输出。 – niemmi

0

尝试将结果存储在变量中,然后将变量写入文件。事情是这样的:

def searchDocs(word): 
    results = [] 
    for document in searchfilesbooks: 
     file = os.path.join(pathWordbooks, document) 
     with open(file, "r") as text: 
      lines = text.readlines() 

     hit_count = 0 
     for line in lines: 
      if re.findall(word, line): 
       hit_count += 1 
       results.append(document + " |" + line) 
     results.append(document + " => " + word + "=> "+ str(hit_count)) 

    with open("WorkWork.txt", "w") as f: 
     f.write('\n'.join(results))