定义一个函数,实现输入一句话,单词之间使用空格隔开,统计出其中各单词的词频数, 并以keyword:count的格式存在一个dict中,返回这个dict。
时间: 2023-06-15 19:06:13 浏览: 131
可以使用Python中的split()函数将句子分割成单词,再使用dict来统计单词出现的频率。以下是实现代码:
```python
def word_count(sentence):
words = sentence.split() # 将句子分割成单词
word_freq = {} # 统计单词频率的字典
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
return word_freq
```
调用函数:
```python
sentence = "Hello world, hello Python. Python is awesome!"
word_freq = word_count(sentence)
print(word_freq)
```
输出结果:
```
{'Hello': 2, 'world,': 1, 'hello': 1, 'Python.': 1, 'Python': 1, 'is': 1, 'awesome!': 1}
```
可以看到,函数成功地统计了句子中各单词的词频数,并以keyword:count的格式存在了一个dict中。
相关问题
定义一个函数,实现输入一句话,单词之间使用空格隔开,统计出其中各单词的词频数,并以keyword:count的格式存在一个dict中,返回这个dict。
可以使用Python自带的collections库中的Counter类来实现。
以下是代码实现:
```python
from collections import Counter
def count_words(sentence):
# 将句子分割成单词
words = sentence.split()
# 使用Counter类统计每个单词的词频
word_counts = Counter(words)
# 将结果转换成字典形式,以keyword:count的格式保存
result = {}
for word, count in word_counts.items():
result[word] = count
return result
```
使用示例:
```python
sentence = "I have a dream that one day this nation will rise up and live out the true meaning of its creed"
result = count_words(sentence)
print(result)
# 输出结果为:{'I': 1, 'have': 1, 'a': 1, 'dream': 1, 'that': 1, 'one': 1, 'day': 1, 'this': 1, 'nation': 1, 'will': 1, 'rise': 1, 'up': 1, 'and': 1, 'live': 1, 'out': 1, 'the': 1, 'true': 1, 'meaning': 1, 'of': 1, 'its': 1, 'creed': 1}
```
题目:定义一个函数,实现输入一句话,单词之间使用空格隔开,统计出其中各单词的词频数, 并以keyword:count的格式存在一个dict中,返回这个dict。 注意 jkl; 不是一个单词,jkl 是一个单词,要把“; + ”等非字符符号去掉 即输入:“abc fjf jkl+ abc abc jkl;” 结果是 {"abc":3,"fjf":1,"jkl":2}
可以按照以下步骤实现该函数:
1. 将输入的字符串按照空格分割成单词列表。
2. 遍历单词列表,去掉每个单词中的非字符符号,例如“;”等。
3. 统计每个单词出现的次数,存储在一个字典中。
4. 返回字典。
代码实现如下:
```python
def count_word_frequency(sentence):
# 将句子按照空格分割成单词列表
words = sentence.split()
# 去掉每个单词中的非字符符号
for i in range(len(words)):
words[i] = ''.join(filter(str.isalpha, words[i]))
# 统计每个单词出现的次数,存储在一个字典中
word_count = {}
for word in words:
if word:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 返回字典
return word_count
```
测试一下:
```python
sentence = "abc fjf jkl abc abc jkl;"
print(count_word_frequency(sentence))
# 输出:{'abc': 3, 'fjf': 1, 'jkl': 2}
```