编写程序实现对特定英文文章(文本文件)的单词数和有效行数的统计,其中要求空行不计数;
def count_words_and_lines(filename):
word_count = 0
line_count = 0
with open(filename, 'r') as file:
for line in file:
stripped_line = line.strip()
if stripped_line:
line_count += 1
words = stripped_line.split()
word_count += len(words)
return word_count, line_count
if _name_ == "_main_":
filename = input("请输入文件名: ") # 例如: "article.txt"
word_count, line_count = count_words_and_lines(filename)
print(f"单词数: {word_count}")
print(f"有效行数: {line_count}")
标签:count,word,words,stripped,filename,英文,Python0035,line,统计
From: https://www.cnblogs.com/yuanxinglan/p/18214339