软工博客26

import os

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

    with open(file_path, 'r', encoding='utf-8') 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

except FileNotFoundError:
    print(f"错误: 文件 {file_path} 未找到。")
except Exception as e:
    print(f"发生未知错误: {e}")

if name == "main":
file_path = 'file.txt'
if os.path.exists(file_path):
result = count_words_and_lines(file_path)
if result is not None:
word_count, line_count = result
print(f"单词数: {word_count}")
print(f"有效行数: {line_count}")
else:
print(f"错误: 文件 {file_path} 未找到。")

posted @ 2025-04-16 17:17  Thanatos。syts  阅读(15)  评论(0)    收藏  举报