python检查句子中是否有相同单词并把相同单词打印出来
时间: 2024-03-20 08:40:09 浏览: 15
你可以使用Python中的字典(dictionary)来完成这个任务。将句子中的单词作为字典的键(key),将单词出现的次数作为字典的值(value),如果单词已经在字典中出现过,就将其值加一。最后遍历字典,将值大于1的键输出即可。
下面是示例代码:
```python
sentence = "Python is a powerful programming language Python"
words = sentence.split() # 将句子分割成单词列表
word_count = {} # 创建一个空字典
# 将单词作为键,单词出现的次数作为值
for word in words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 遍历字典,输出值大于1的键
for word, count in word_count.items():
if count > 1:
print(word)
```
输出结果为 "Python",因为这个句子中有重复的单词 "Python"。
相关问题
python 检查一个句子中是否有相同的单词
可以使用Python中的集合(set)来判断一个句子中是否有相同的单词,因为集合会自动去重,所以如果把句子中的单词放入集合中,如果集合的长度和句子中单词数量不同,说明有重复的单词。
下面是一个示例代码:
```python
sentence = "Python is a powerful programming language"
words = sentence.split() # 将句子分割成单词列表
word_set = set(words) # 将单词列表转化为集合
if len(words) == len(word_set):
print("句子中没有重复的单词")
else:
print("句子中有重复的单词")
```
输出结果为 "句子中没有重复的单词",因为这个句子中没有重复的单词。
如果换成下面这个句子:
```python
sentence = "Python is a powerful programming language Python"
```
输出结果就为 "句子中有重复的单词",因为这个句子中有重复的单词 "Python"。
python 中两个列表查找相同单词
可以使用 set() 函数将两个列表转换为集合,然后使用交集运算符 & 来查找两个列表中相同的单词。以下是示例代码:
```
list1 = ['apple', 'orange', 'banana', 'pear']
list2 = ['banana', 'grape', 'orange', 'watermelon']
set1 = set(list1)
set2 = set(list2)
common_words = set1 & set2
print(common_words)
```
输出结果为:
```
{'orange', 'banana'}
```
这表示在两个列表中都出现过的单词是 'orange' 和 'banana'。
相关推荐
![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)