请输入一个字符串以确定同一单词的出现次数。(代码+结果截图)python
时间: 2023-05-31 12:02:22 浏览: 61
抱歉,作为AI语言模型,我无法提供截图功能。以下是python代码:
```python
s = input("请输入一个字符串:")
word_dict = {}
for word in s.split():
if word in word_dict:
word_dict[word] += 1
else:
word_dict[word] = 1
for word, count in word_dict.items():
print(word, count)
```
这段代码会先让用户输入一个字符串,然后将字符串分割成单词,并统计每个单词出现的次数,最后输出每个单词及其出现次数。例如,如果用户输入了字符串 "I am a student. He is also a student.",则输出结果为:
```
I 1
am 1
a 2
student. 2
He 1
is 1
also 1
```
相关问题
python删除重复单词_Python数据框:删除Python列中同一单元格中的重复单词
可以使用Python的字符串处理函数和pandas库来删除数据框中同一单元格中的重复单词。下面是一个简单的代码示例:
```python
import pandas as pd
# 创建包含重复单词的数据框
df = pd.DataFrame({'col1': ['python is great', 'python is awesome', 'data science is great']})
# 删除col1列中的重复单词
df['col1'] = df['col1'].apply(lambda x: ' '.join(sorted(set(x.split()), key=x.split().index)))
# 打印输出结果
print(df)
```
输出结果:
```
col1
0 python is great
1 python is awesome
2 data science is great
```
使用lambda函数和字符串处理函数split()将字符串分割成单词列表,使用set()函数删除重复单词,再使用sorted()函数和index()方法按单词在原始字符串中的顺序排序单词列表,最后使用join()函数将单词列表拼接成一个字符串。
定义函数acron(phrase),输入英文短语,同一行输出每一个单词的首字母大写,中间没有空格
好的,下面是实现函数acron(phrase)的Python代码:
```python
def acron(phrase):
words = phrase.split()
acron = ""
for word in words:
acron += word[0].upper()
return acron
```
这个函数首先把输入的短语按照空格分成单词列表,然后遍历每个单词,把它的首字母大写加入到一个字符串中,最后返回这个字符串作为结果。