对于我下面的代码,我想打印出一个完整的句子,其中出现了我的单词列表中的某些单词,以及它会将每个特定单词下面的单词计数打印成.txt文件。我在终端上成功实现了这一点,但我真的很难将它变成.txt。目前我似乎只能打印出.txt中的单词计数,但句子仍在打印到终端,有人知道我可能在哪里出错吗?抱歉,我缺乏初学者学习python的知识。谢谢
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()
答案 0 :(得分:1)
如果您使用print(document + " |" + line, end="")
打印句子,则会忘记file
参数。添加它应该可以解决问题:
print(document + " |" + line, end="", file=lush)
答案 1 :(得分: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))