我的朋友确实写了每个字的佣金和费用。我想写一个脚本,可以为他做计算。我正在尝试计算文本文件中的每个单词。它仅读取第一行,而忽略其余的行。
我对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()
想要的结果是使脚本在无限循环中运行,以重新检查文本文件的字数统计,并输出计算出的成本。唯一的问题是弄清楚这一点。
答案 0 :(得分:2)
这是用来数词的:
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")