python用字典来统计词频
时间: 2023-07-12 10:48:08 浏览: 136
是的,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}
```
可以看到,字典中的键为单词,值为该单词出现的次数。
相关问题
python123用字典来统计词频
Python的字典非常适合用于统计词频,因为它允许我们通过键值对的方式来存储数据。假设我们有一个字符串列表,包含了一些文本,我们可以按照以下步骤来统计每个单词的频率:
```python
# 创建一个空字典来存放词频
word_freq = {}
# 假设text_list是一个包含文本的列表
for text in text_list:
# 将文本分割成单词列表,这里通常使用split()函数,如果需要考虑标点符号,可以先用正则表达式预处理
words = text.split()
# 遍历单词列表
for word in words:
# 如果单词已经在字典中,则将其计数加一;如果不在,添加新键并设置计数为1
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
# 现在word_freq字典中包含了每个单词及其出现次数
```
最后,你可以打印出整个字典,查看每个单词的词频。如果你想要找出最常见的几个单词,还可以使用`most_common()`函数。
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)]
```
可以看到,结果按照频率从高到低排序。
阅读全文
相关推荐













