如何用python类实现单词的统计
时间: 2024-05-15 09:17:30 浏览: 19
您好,您可以使用Python中的字典(dictionary)对单词进行统计。可以将每个单词作为字典的键,出现次数作为值。具体实现如下示例代码:
```
class WordCount:
def __init__(self):
self.word_count = {}
def count_words(self, words):
for word in words:
if word not in self.word_count:
self.word_count[word] = 1
else:
self.word_count[word] += 1
return self.word_count
```
其中,`__init__()` 方法用于初始化一个空字典 `word_count`,`count_words()` 方法接收一个字符串列表 `words`,并统计每个单词的出现次数。最后,将字典返回。使用示例如下:
```
words = ['apple', 'banana', 'apple', 'orange']
word_count = WordCount()
print(word_count.count_words(words))
```
输出结果为:
```
{'apple': 2, 'banana': 1, 'orange': 1}
```
以上示例代码仅作参考,如有不妥之处,请指正。
相关问题
python实现单词统计
以下是一个Python程序,可以统计给定文本中每个单词出现的次数:
```python
text = "This is a sample text with several words. It has some repeated words, like words and sample."
# 将所有单词转换为小写并分割文本
words = text.lower().split()
# 创建一个字典来存储每个单词的出现次数
word_count = {}
# 遍历每个单词并更新字典
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 打印每个单词及其出现的次数
for word, count in word_count.items():
print(word, count)
```
输出:
```
this 1
is 1
a 1
sample 2
text 1
with 1
several 1
words. 1
it 1
has 1
some 1
repeated 1
words, 1
like 1
and 1
```
用python实现英文词频统计
可以使用Python中的collections模块中的Counter类来实现英文词频统计。具体步骤如下:
1. 读取英文文本文件,将其内容存储到一个字符串中。
2. 将字符串中的标点符号和换行符替换为空格。
3. 将字符串中的所有字母转换为小写。
4. 将字符串按照空格分割成单词列表。
5. 使用Counter类统计每个单词在列表中出现的次数。
6. 输出结果。
下面是一个示例代码:
```python
import collections
# 读取文件内容
with open('text.txt', 'r') as file:
text = file.read()
# 将标点符号和换行符替换为空格
text = text.replace('\n', ' ')
for ch in '.,?!():;':
text = text.replace(ch, ' ')
# 将所有字母转换为小写
text = text.lower()
# 按照空格分割成单词列表
words = text.split()
# 统计单词出现次数
counter = collections.Counter(words)
# 输出结果
for word, count in counter.most_common():
print(word, count)
```
其中,text.txt是待统计的英文文本文件。输出结果按照单词出现次数从高到低排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)