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

标签 python python-3.x

我的 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/

相关文章:

python - NLTK:conllstr2tree 无法正常工作(Python3)

javascript - 使用 NPM install 从文件安装 NodeJS 包

python - Django AllAuth 自定义模板不被识别

python - 多表密码的 for 循环末尾未打印文本

python - h5py文件上传中,np.array(file[key][ :]) and np. array(file[key]) 有什么区别

python - python 中的 smtplib.server.sendmail 函数引发 UnicodeEncodeError : 'ascii' codec can't encode character

python - python shell 可以有一些预输入吗?

python - 如何在Python上制作具有不同大小的最后一个参数的3D矩阵

python - 如何使用 Mysql Python 连接器检索二进制数据?

python - 在 Python 中,编写可重用代码以提供与对象列表交互的方法的最佳方法是什么?