用python如何去掉集合中重复单词
时间: 2023-03-19 07:20:50 浏览: 54
可以使用Python的集合模块,这样可以轻松地去掉集合中的重复单词。下面是一个简单的例子:my_set = set(['hello', 'world', 'hello']) print(my_set) # 输出 {'hello', 'world'}
相关问题
python:删除重复单词
在 Python 中,可以使用集合(set)来删除重复单词。将字符串转换成单词列表后,将其转换为集合,然后再将集合转换回列表即可。下面是一个示例代码:
```python
sentence = "this is a sentence with duplicate words this is a sentence without duplicates"
words = sentence.split() # 将字符串转换成单词列表
unique_words = list(set(words)) # 将单词列表转换成集合,再转换回列表
print(' '.join(unique_words)) # 将列表转换成字符串输出
```
输出结果:
```
sentence this is a without duplicate words
```
在这个例子中,我们定义了一个字符串 `sentence`,其中包含重复的单词。首先,我们使用 `split()` 方法将字符串转换成单词列表,然后使用 `set()` 函数将其转换成集合,集合会自动去重。最后,我们使用 `list()` 函数将集合转换回列表,再使用 `join()` 方法将列表转换成字符串输出。
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()方法统计集合中元素的数量即为不重复单词数量。