python中的简单单词计数器程序

时间:2021-03-16 15:50:43

标签: python text-files

我尝试创建一个非常简单的程序来计算您所写的字数。当我运行我的代码时,我没有收到任何错误,问题是它总是说:“单词数为 0”,而它显然不是 0。我尝试添加它,看看它是否真的从中读取了任何内容文件: print(data) 。它不打印任何东西):所以读取部分肯定有问题。

print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")

info = f.write(words)
data = z.read()
res = len(data.split())

print("the numbers of words are " + str(res))
f.close()

提前谢谢

2 个答案:

答案 0 :(得分:1)

使用 f 写入 f.write 后,您应该在调用 f 之前使用 f.close 关闭 z.readSee here

答案 1 :(得分:1)

这是因为您在写入文件后还没有关闭它。在使用 f.close()

之前使用 z.read()

代码:

print("copy ur text down below")
words = input("")
f = open("data.txt", "w+")
z = open("data.txt", "r+")

info = f.write(words)
f.close() # closing the file here after writing
data = z.read()
res = len(data.split())

print("the numbers of words are " + str(res))
f.close()

输出:

copy ur text down below
hello world
the numbers of words are 2