python123统计单词的数量
时间: 2023-10-12 08:15:49 浏览: 72
您好!关于统计单词数量的问题,可以使用Python编程语言来实现。您可以使用Python自带的字符串操作函数和列表操作函数来完成这个任务。以下是实现代码示例:
```python
# 定义一个字符串
text = "Python is a widely used high-level programming language for general-purpose programming."
# 将字符串转为小写
text = text.lower()
# 将字符串按空格分割成单词列表
words = text.split()
# 定义一个字典,用于存储每个单词的数量
word_dict = {}
# 统计每个单词出现的次数
for word in words:
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
# 输出结果
for word, count in word_dict.items():
print(word, ":", count)
```
该代码会输出以下结果:
```
python : 1
is : 1
a : 1
widely : 1
used : 1
high-level : 1
programming : 2
language : 1
for : 1
general-purpose : 1
```
相关问题
python统计单词数量
可以使用Python中的字典来统计单词数量,具体步骤如下:
1. 读取文本文件,并将文件内容存储到一个字符串变量中;
2. 将字符串变量中的所有单词分割出来,可以使用Python的 split() 函数;
3. 遍历分割出来的每个单词,使用字典来记录每个单词出现的次数;
4. 最后输出每个单词出现的次数。
以下是一个示例代码:
```python
# 读取文件内容
with open('example.txt', 'r') as f:
content = f.read()
# 分割单词
words = content.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(f'{word}: {count}')
```
注意,上述代码中的 `example.txt` 是需要统计单词数量的文本文件,可以根据实际情况进行替换。
python统计不重复单词数量
可以使用Python中的集合(set)来统计不重复单词数量。代码如下:
```
text = "This is a sample text with several words. This is another sentence with some words."
words = text.split()
num_unique_words = len(set(words))
print("Number of unique words:", num_unique_words)
```
输出结果为:
```
Number of unique words: 12
```
其中,text是待统计的文本,使用split()方法将文本分割成单词列表,然后使用set()方法将列表转换为集合,最后使用len()方法统计集合中元素的数量即为不重复单词数量。
相关推荐
![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)