编写一个有相似功能的程序。
时间: 2024-10-20 19:08:28 浏览: 16
当然可以,假设您想要编写一个简单的文本分析程序,比如统计一段英文文本中各个单词出现的次数。这是一个基本的Python示例:
```python
def word_count(text):
"""
统计给定文本中每个单词的出现次数
"""
# 分割文本成单词列表
words = text.split()
# 初始化空字典存储词频
word_freq = {}
# 遍历单词列表
for word in words:
# 将单词转换为小写并去除标点符号
cleaned_word = word.lower().strip(".,!?;:")
# 如果单词已经在字典中,则加一;否则添加新键值对
if cleaned_word in word_freq:
word_freq[cleaned_word] += 1
else:
word_freq[cleaned_word] = 1
return word_freq
# 测试函数
text = "Hello world! This is a sample text for word count program. It will demonstrate how to count the occurrences of each word."
word_counts = word_count(text)
# 输出结果
for word, frequency in word_counts.items():
print(f"'{word}': {frequency}")
#
阅读全文