python统计不重复单词数量
时间: 2023-09-22 16:11:14 浏览: 128
可以使用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()方法统计集合中元素的数量即为不重复单词数量。
相关问题
python怎么统计不包括重复的单词总数
可以使用Python中的set()函数来去除列表中的重复元素,然后使用len()函数来获取不同单词的数量,如下所示:
```python
text = "This is a sample text with some repeated words in it. The repeated words will be counted only once."
words = text.split()
unique_words = set(words)
count = len(unique_words)
print("The total number of unique words is:", count)
```
输出结果为:
```
The total number of unique words is: 16
```
其中,text是待处理的文本字符串,words是将其分割成单词后得到的列表,unique_words则是去重后的单词集合,count则是unique_words的长度,即不同单词的数量。
给我一段python代码,输入一些单词,统计不重复的单词
当然,这是一段可以统计不重复单词的 Python 代码:
```python
words = input("请输入一些单词,用空格隔开:")
word_list = words.split()
word_set = set(word_list)
print("不重复的单词数量为:", len(word_set))
```
这段代码首先接收用户输入的一串单词,然后将其使用 `split()` 方法分割成一个单词列表。接下来,我们将这个列表转换为一个集合,这样就去除了其中的重复元素。最后,我们输出集合的长度,即不重复单词的数量。