繁体   English   中英

python中的简单字计数器程序

[英]Simple word counter program in python

我试图创建一个非常简单的程序来计算你写的单词。 当我运行我的代码时,我没有收到任何错误,问题是它总是说:“单词的数量是 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()

提前谢谢

在使用f.write写入f之后,您应该在调用f.close之前使用z.read关闭f 见这里

这是因为您在写入文件后还没有关闭文件。 在使用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()

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM