python统计不重复的单词个数
时间: 2023-10-30 15:05:08 浏览: 63
您好!我理解您的问题是关于Python如何统计不重复的单词个数。这可以通过以下代码实现:
```python
text = "This is a sample sentence to count the number of unique words."
words = text.split()
unique_words = set(words)
num_unique_words = len(unique_words)
print("Number of unique words:", num_unique_words)
```
请注意,以上代码会将所有单词都转换为小写字母,并且标点符号将被视为单词的一部分。如果您需要将其作为函数并应用于其他文本,请参考以下示例代码:
```python
def count_unique_words(text):
words = text.lower().split()
unique_words = set(words)
num_unique_words = len(unique_words)
return num_unique_words
text = "This is a sample sentence to count the number of unique words."
num_unique_words = count_unique_words(text)
print("Number of unique words:", num_unique_words)
```
希望我的解答能够帮助您!
相关问题
用python统计不重复的单词个数
可以使用Python的collections模块下的Counter类来统计单词个数,然后再计算不重复单词的个数。
以下是示例代码:
```python
from collections import Counter
text = "This is a sample text with several words and repeated words"
# 使用split()方法将文本分解为单词列表
words_list = text.split()
# 使用Counter类统计单词出现次数
word_counts = Counter(words_list)
# 计算不重复单词的个数
unique_words = len(word_counts)
print("文本中不重复的单词个数为:", unique_words)
```
输出结果为:
```
文本中不重复的单词个数为: 9
```
在这个例子中,文本中有9个不重复的单词。
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()方法统计集合中元素的数量即为不重复单词数量。