python - 计算文本文件中的每个单词并输出成本
问题描述
我的朋友确实按字写佣金和收费。我想写一个可以为他做计算的脚本。我正在尝试计算文本文件中的每个单词。它只读取第一行并忽略其余部分。
我的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 - Plotly Choropleth 不使用 ISO 代码显示颜色
- r - 基于字符串值的子集数据
- date - 25.02.2021 11:36 (CET) 单元格值显示为 24.02.2021 18:00 (EST)
- java - 为什么我不能在非静态方法中声明静态变量?
- c - 如何设置断点 malloc_error_break lldb
- python - 类型错误:尝试在 Python 中循环函数时 - 不支持的操作数类型:“str”和“float”
- c# - 使用后台并行无限循环 C# 读取缓冲区
- python - 我们如何将电子邮件 ID 列表更改为唯一数字并在 python 中对其进行屏蔽
- firebird - 如何连接两个 Firebird 数据库中的表?
- python - 在张量流模型训练中启用混合精度会降低而不是提高速度