python对字符串进行词频统计
时间: 2023-12-10 16:04:21 浏览: 34
可以使用Python中的collections模块中的Counter类来进行字符串的词频统计,具体代码如下:
```python
from collections import Counter
string = "This is a sample string for word frequency count"
# 将字符串拆分成单词列表
words = string.split()
# 使用Counter类进行词频统计
word_counts = Counter(words)
# 输出结果
print(word_counts)
```
输出结果为:
```
Counter({'This': 1, 'is': 1, 'a': 1, 'sample': 1, 'string': 1, 'for': 1, 'word': 1, 'frequency': 1, 'count': 1})
```
可以看到,该代码将字符串拆分成单词列表后,使用Counter类对单词列表进行词频统计,最后输出了每个单词出现的次数。
相关问题
python对字符串进行词频统计并绘制词云图
要进行字符串词频统计并绘制词云图,可以使用Python中的`wordcloud`和`jieba`库。以下是一个简单的示例代码:
```python
import jieba
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
# 输入文本
text = "这是一段需要进行词频统计并绘制词云图的测试文本,希望能够得到好的结果。"
# 分词
words = jieba.cut(text)
# 统计词频
word_counts = Counter(words)
# 生成词云图
wc = WordCloud(background_color="white", max_words=2000, width=1024, height=768, font_path='msyh.ttc')
wc.generate_from_frequencies(word_counts)
# 显示词云图
plt.imshow(wc, interpolation='bilinear')
plt.axis("off")
plt.show()
```
运行以上代码,就可以得到一个简单的词云图了。你可以根据自己的需求,对代码进行修改和优化。
python用内置函数进行英文词频统计
Python中可以使用collections模块中的Counter类来进行英文词频统计。具体操作如下:
```python
from collections import Counter
# 定义文本字符串
text = "The quick brown fox jumps over the lazy dog. The dog slept over the verandah."
# 将文本字符串转为小写并分割成单词
words = text.lower().split()
# 使用Counter类统计单词出现的频率
word_counts = Counter(words)
# 输出结果
print(word_counts)
```
上述代码中,首先将文本字符串转为小写并分割成单词。然后使用Counter类对单词进行统计,得到每个单词出现的次数。最后输出结果。输出结果如下:
```
Counter({'the': 3, 'over': 2, 'dog.': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'lazy': 1, 'dog': 1, 'slept': 1, 'verandah.': 1})
```
其中,Counter对象是一个字典,键为单词,值为该单词出现的频率。可以通过调用most_common方法,按照出现次数从高到低输出前n个出现频率最高的单词,代码如下:
```python
# 输出出现频率最高的前3个单词
print(word_counts.most_common(3))
```
输出结果如下:
```
[('the', 3), ('over', 2), ('dog.', 1)]
```
以上代码展示了如何使用Python内置函数进行英文词频统计。