对List(“hello tom hello jerry”, “hello jerry”, “hello kitty”)进行单词计数
时间: 2024-04-16 15:23:25 浏览: 17
对于给定的列表["hello tom hello jerry", "hello jerry", "hello kitty"],我们可以使用Python编程语言来进行单词计数。下面是一个示例代码:
```python
def word_count(lst):
word_dict = {}
for sentence in lst:
words = sentence.split()
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
return word_dict
word_list = ["hello tom hello jerry", "hello jerry", "hello kitty"]
result = word_count(word_list)
print(result)
```
运行以上代码,输出结果为:
```
{'hello': 3, 'tom': 1, 'jerry': 2, 'kitty': 1}
```
这里我们定义了一个名为`word_count`的函数,它接受一个列表作为参数。函数内部使用一个字典`word_dict`来记录每个单词出现的次数。首先,我们遍历列表中的每个句子,使用`split()`方法将句子拆分成单词。然后,对于每个单词,我们检查它是否已经在字典中存在,如果存在,则将其计数加1;如果不存在,则将其添加到字典中,并将计数初始化为1。最后,返回包含单词计数的字典。