Python 如何打印到.txt文件
对于下面的代码,我想打印出一个完整的句子,其中出现了我单词列表中的某些单词,它还可以将每个特定单词下面的单词数打印到一个.txt文件中。我在终端上成功地实现了这一点,但我真的很难把它转换成一个.txt文件。目前,我似乎只能让它打印出.txt中的字数,但句子仍在打印到终端,有人知道我可能会出错吗?很抱歉,我对初学者学习python缺乏知识。谢谢Python 如何打印到.txt文件,python,python-3.x,text,printing,text-mining,Python,Python 3.x,Text,Printing,Text Mining,对于下面的代码,我想打印出一个完整的句子,其中出现了我单词列表中的某些单词,它还可以将每个特定单词下面的单词数打印到一个.txt文件中。我在终端上成功地实现了这一点,但我真的很难把它转换成一个.txt文件。目前,我似乎只能让它打印出.txt中的字数,但句子仍在打印到终端,有人知道我可能会出错吗?很抱歉,我对初学者学习python缺乏知识。谢谢 import re, os pathWordLists = "E:\\Python\WordLists" searchfilesLists = os.
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()
如果使用
print(document+“|”+line,end=”“)打印句子
您忘记了文件
参数。添加它可以解决以下问题:
print(document + " |" + line, end="", file=lush)
尝试将结果存储在变量中,然后将变量写入文件。大概是这样的:
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))
我已经将它添加到print(document+“|”+line,end=”,file=lush)和print(document+“=>”+word+“=>”+str(hit_count),file=lush)中,现在它可以完美地将它们打印到.txt中,但出于某种原因,它说“New Text document.txt=>”无论如何都可以解决这个问题。非常感谢您的帮助,因为我需要知道您正在扫描的目录的内容以及预期的输出。