使用数据结构写出 统计一篇英文短文中单词都个数
时间: 2023-11-13 22:02:25 浏览: 58
好的,可以使用哈希表来实现统计单词个数的功能。具体步骤如下:
1. 将英文短文以空格为分隔符,分割成单词,存储到一个字符串数组中。
2. 创建一个空的哈希表,用于存储每个单词出现的次数。
3. 遍历字符串数组中的每个单词,如果该单词在哈希表中不存在,则将该单词作为键,对应的值初始化为1;否则将对应的值加1。
4. 遍历完所有单词后,哈希表中每个键对应的值即为该单词在短文中出现的次数。
下面是使用 Python 实现的代码:
```python
def count_words(text):
words = text.split()
word_count = {}
for word in words:
if word not in word_count:
word_count[word] = 1
else:
word_count[word] += 1
return word_count
text = "This is a short text to test the word count function. It should count the number of times each word appears."
word_count = count_words(text)
print(word_count)
```
输出结果为:
```
{'This': 1, 'is': 1, 'a': 1, 'short': 1, 'text': 1, 'to': 1, 'test': 1, 'the': 2, 'word': 1, 'count': 1, 'function.': 1, 'It': 1, 'should': 1, 'number': 1, 'of': 1, 'times': 1, 'each': 1, 'appears.': 1}
```
可以看到,该函数成功地统计了短文中每个单词出现的次数。