对于给定的文件sample.txt,统计其中单词的个数,以及给定单词出现的次数。
时间: 2023-11-27 12:50:10 浏览: 24
以下是Python的实现代码:
```python
# 统计单词个数和给定单词出现次数的函数
def count_words(file_name, target_word):
word_count = 0
target_count = 0
with open(file_name, 'r') as f:
# 读取文件内容
content = f.read()
# 统计单词个数
word_count = len(content.split())
# 统计给定单词出现次数
target_count = content.count(target_word)
return word_count, target_count
# 调用函数,传入文件名和目标单词
file_name = 'sample.txt'
target_word = 'Python'
word_count, target_count = count_words(file_name, target_word)
# 输出结果
print("单词总数为:", word_count)
print("单词'{}'的出现次数为:{}".format(target_word, target_count))
```
其中,`count_words()`函数接受文件名和目标单词作为参数,使用`with open()`语句打开文件并读取文件内容。然后,使用`split()`方法分割文件内容,得到单词列表,再使用`len()`函数计算单词个数。接着,使用`count()`方法统计目标单词出现的次数。最后,函数返回单词总数和目标单词出现次数。
在调用函数时,传入文件名和目标单词,得到函数返回值后,使用`print()`函数输出结果。