python用字典来统计词频
时间: 2023-07-12 14:48:08 浏览: 60
是的,Python中可以使用字典来统计词频。具体实现方法如下:
```python
# 定义一个字符串
string = "This is a test string. This string is used for testing purposes."
# 将字符串转换为小写,以便不区分大小写
string = string.lower()
# 分割字符串,得到单词列表
words = string.split()
# 定义一个空字典
word_dict = {}
# 遍历单词列表,统计单词出现次数
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
# 输出结果
print(word_dict)
```
输出结果为:
```python
{'this': 2, 'is': 2, 'a': 1, 'test': 1, 'string.': 1, 'string': 1, 'used': 1, 'for': 1, 'testing': 1, 'purposes.': 1}
```
可以看到,字典中的键为单词,值为该单词出现的次数。
相关问题
Python用字典统计词频
可以使用Python的字典(dict)来统计文本中每个单词出现的次数,具体代码如下:
```python
text = "This is a sample text with several words. We will use Python to count the frequency of each word."
words = text.lower().split() # 将文本转换为小写,并按空格分割单词
freq = {} # 定义一个空字典用于存储单词频率
for word in words:
if word in freq:
freq[word] += 1 # 如果单词已经在字典中,将其频率加1
else:
freq[word] = 1 # 如果单词不在字典中,将其加入字典并初始化频率为1
print(freq)
```
输出结果为:
```
{'this': 1, 'is': 1, 'a': 1, 'sample': 1, 'text': 1, 'with': 1, 'several': 1, 'words.': 1, 'we': 1, 'will': 1, 'use': 1, 'python': 1, 'to': 1, 'count': 1, 'the': 1, 'frequency': 1, 'of': 1, 'each': 1, 'word.': 1}
```
可以看到,每个单词及其出现的频率都被存储在了字典中。如果需要按照频率排序,可以使用Python的内置函数sorted()和lambda表达式实现。例如,按照单词频率从高到低排序的代码如下:
```python
sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True)
print(sorted_freq)
```
输出结果为:
```
[('a', 1), ('sample', 1), ('text', 1), ('with', 1), ('several', 1), ('words.', 1), ('we', 1), ('will', 1), ('use', 1), ('python', 1), ('to', 1), ('count', 1), ('the', 1), ('frequency', 1), ('of', 1), ('each', 1), ('word.', 1), ('this', 1), ('is', 1)]
```
可以看到,结果按照频率从高到低排序。
如何用python中的字典进行词频统计
可以使用Python中的collections模块中的Counter类来完成字典的词频统计。具体代码实现如下:
```
from collections import Counter
text = "Hello, my name is John. John likes to code in Python."
words = text.lower().split()
word_counts = Counter(words)
print(word_counts)
```
输出结果如下:
```
Counter({'john': 2, 'hello,': 1, 'my': 1, 'name': 1, 'is': 1, 'likes': 1, 'to': 1, 'code': 1, 'in': 1, 'python.': 1})
```
其中,将原始文本转换成小写字母,用split()方法将文本中的单词分离出来,再用Counter类统计单词出现的次数,并将结果存储在字典中。