gpt4 book ai didi

python - 计算文本文件中的每个单词并输出成本

转载 作者:行者123 更新时间:2023-12-01 01:12:08 24 4
gpt4 key购买 nike

我的 friend 收取写作佣金并按字收费。我想写一个脚本来为他进行计算。我正在尝试计算文本文件中的每个单词。它只读取第一行并忽略其余行。

我的Python知识很少,但我认为我走在正确的道路上。我想我必须以某种方式使用 readlines() 每隔几秒钟重新读取文件。

import math
import time

def count():
txt = input("What is your file name?\nNote: file must be in same location as script\n")
file = open(txt,"r")
word_list = file.read().split(',')
word_count = len(word_list)
words = word_count
file.close
return words


def output(items):
file = open("livecost.txt","w")
total = items * .02
file.write(format(total, ".2f"))




def main():
num = int()
print("Lanching script")
while num < 1000000:
output(count())
num = num + 1
time.sleep(1)

main()

想要的结果是脚本在重新检查文本文件字数的无限循环中运行,并输出计算出的成本。唯一的问题是弄清楚这一点。

最佳答案

这足以计算单词数:

def countwords(txtdir):
with open(txtdir) as f:
return len(f.read().split())

没有输出功能更好

def main(txtdir):
print("Lanching script")
with open("livecost.txt","w") as f:
for num in range(1000000):
f.write("{} \n".format(countwords(txtdir)))
time.sleep(1)

完整代码:

import time,datetime

def countwords(txtdir):
with open(txtdir) as f:
return len(f.read().split())

def main(txtdir):
print("Lanching script")
with open("livecost.txt","w") as f:
for num in range(1000000):
f.write("{}\t{}\n".format(datetime.datetime.now(),countwords(txtdir)))
time.sleep(1)

main("What is your file name?\nNote: file must be in same location as script\n")

关于python - 计算文本文件中的每个单词并输出成本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54756373/

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