gpt4 book ai didi

python - 如何打印到 .txt

转载 作者:太空宇宙 更新时间:2023-11-03 16:40:07 30 4
gpt4 key购买 nike

对于下面的代码,我想打印出一个完整的句子,其中出现了我的单词列表中的某些单词,并且它将每个特定单词下面的单词计数打印到 .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()

最佳答案

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

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

关于python - 如何打印到 .txt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36879376/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com