簡體   English   中英

計算文本文件中的每個單詞並輸出費用

[英]Counting every word in a text file and outputting a cost

我的朋友確實寫佣金和每個單詞收費。 我想寫一個腳本,可以為他做計算。 我正在嘗試計算文本文件中的每個單詞。 它僅讀取第一行,而忽略其余的行。

我的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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM