[英]count words of text file in python3
我正在学习python,我想创建一个程序来计算文本文件中单词的总数。
fname = input("Enter file name: ")
with open(fname,'r') as hand:
for line in hand:
lin = line.rstrip()
wds = line.split()
print(wds)
wordCount = len(wds)
print(wordCount)
我的文本文件的内容是:您好,这是我的测试程序,我是python新手,谢谢
当我在分割后打印wds
。 我从文本文件中获取拆分后的文本,但是当我尝试打印长度时,我只是得到了最后一个单词的长度。
您需要初始化wordCount = 0
,然后在for loop
每次迭代时都需要添加到wordCount中。 像这样:
wordCount = 0
for line in hand:
lin = line.rstrip()
wds = lin.split()
print(wds)
wordCount += len(wds)
print(wordCount)
有四件事要做:
因此,只需按该顺序执行;)
with open(fname,'r') as f:
words = [word for line in f
for word in line.strip().split()]
print(f"Number of words: {len(words)}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.