增补博客 第三篇 python 英文统计

编写程序实现对特定英文文章(文本文件)的单词数和有效行数的统计,其中要求空行不计数;

def count_words_and_lines(file_path):
    word_count = 0
    line_count = 0

    # 打开文件
    with open(file_path, 'r') as file:
        for line in file:
            line = line.strip()  # 去除首尾空白字符

            # 空行不计数
            if line:
                line_count += 1

                # 使用空格分割单词
                words = line.split()
                word_count += len(words)

    return word_count, line_count

# 输入要处理的文本文件路径
file_path = input("请输入文本文件路径:")

try:
    # 统计单词数和有效行数
    word_count, line_count = count_words_and_lines(file_path)
    print(f"单词数: {word_count}")
    print(f"有效行数: {line_count}")
except FileNotFoundError:
    print("找不到指定的文件,请确认路径是否正确。")
except Exception as e:
    print(f"发生错误: {e}")

  

posted @ 2024-06-14 12:03  财神给你送元宝  阅读(22)  评论(0)    收藏  举报