首页 > 解决方案 > 计算文本文件中的每个单词并输出成本

问题描述

我的朋友确实按字写佣金和收费。我想写一个可以为他做计算的脚本。我正在尝试计算文本文件中的每个单词。它只读取第一行并忽略其余部分。

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

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

标签: pythonpython-3.x

解决方案


这足以计算单词:

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

推荐阅读