MST

星途 面试题库

面试题:Python中如何利用文件内容统计特定单词出现次数

假设给定一个文本文件,文件中包含若干英文单词,请用Python编写代码,实现统计文件中某个特定单词出现的次数。要求正确处理文件读取、单词分割以及大小写等问题。
50.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def count_specific_word(file_path, target_word):
    try:
        word_count = 0
        with open(file_path, 'r', encoding='utf-8') as file:
            for line in file:
                words = line.strip().split()
                for word in words:
                    if word.lower() == target_word.lower():
                        word_count += 1
        return word_count
    except FileNotFoundError:
        print(f"文件 '{file_path}' 未找到。")
        return 0


# 示例用法
file_path = 'your_file.txt'
target_word = 'example'
count = count_specific_word(file_path, target_word)
print(f"单词 '{target_word}' 出现的次数为: {count}")