My friend does writing commissions and charges per word. I wanted to write a script that could do the calculations for him. I am trying to count every individual word in the text file. It reads the first line only and ignores the rest.
My python knowledge is minimal, but I think I'm on the right track. I think I have to somehow use readlines() to re-read the file every couple seconds.
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()
The wanted outcome is for the script to run in an infinite loop of rechecking the text file wordcount, and outputting the calculated cost. The only problem is figuring that out.
this is enaugh for counting words:
def countwords(txtdir):
with open(txtdir) as f:
return len(f.read().split())
its better with no output function
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)
full code:
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")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.