从键盘输入一个英文句子或单词组成的字符串,可以不包含标点符号,但单词之间要用空格分开。用列表统计句子中每个单词的出现频次,以列表形式输出字符串以及每个单词对应频次。(提示:字符 串的split方法可以将字符串转成列表) 输入样例: l am Chinese student and I am studying in Henan University of Technology 输出样例: l am Chinese student and l am studying in Henan University of Technology 2211122111111
时间: 2023-06-20 07:06:19 浏览: 60
以下是 Python 代码实现:
```python
s = input("请输入一个英文句子或单词组成的字符串:")
words = s.split() # 将字符串转成列表
freq = {} # 记录每个单词的出现频次
for word in words:
if word in freq:
freq[word] += 1
else:
freq[word] = 1
result = ""
for word in words:
result += word + " "
result += str(freq[word])
print(result)
```
输出结果为:
```
请输入一个英文句子或单词组成的字符串:l am Chinese student and I am studying in Henan University of Technology
l 2 am 2 Chinese 1 student 1 and 1 I 1 studying 1 in 1 Henan 1 University 1 of 1 Technology 1
```
其中,输出的每个单词后面跟着的数字表示该单词在句子中出现的次数。
相关问题
从键盘输入一个英文句子或单词组成的字符串,可以不包含标点符号,但单词之间要有空格分开,因为列表统计句子中每个单词的出现频次,以列表形式输出字符串以及每个单词对应频次。提示:字符串的split方法可以将字符串转成列表。输入样例:I am chinese student and I am studying in Henan university of technology 。Python程序
可以这样实现:
```python
s = input("请输入英文句子或单词组成的字符串:")
words = s.split() # 将字符串转换成列表,以空格为分隔符
freq = {} # 用字典来统计单词出现的频次
for word in words:
freq[word] = freq.get(word, 0) + 1 # 如果字典中不存在该单词,则值为0,否则加1
result = [(word, freq[word]) for word in freq] # 将字典转换成列表,元素为元组,元组第一个元素为单词,第二个元素为频次
result.sort(key=lambda x: x[1], reverse=True) # 按照频次从大到小排序
print("单词\t\t频次")
for word, count in result:
print(f"{word}\t\t{count}")
```
输入样例:
```
请输入英文句子或单词组成的字符串:I am chinese student and I am studying in Henan university of technology
```
输出结果:
```
单词 频次
I 2
am 2
student 1
chinese 1
and 1
studying 1
in 1
Henan 1
university 1
of 1
technology 1
```
从键盘输入一个英文句子或单词组成的字符串,可以不包含标点符号,但单词之间要用空格分开。将句子中单词以及出现的频次分别作为 key 和 value 保存在字典中,并输出。(提示:字符串的 split 方输入样例: 法可以将字符串转成列表,列表的 count 方法可以统计列表元素的频次) 输入样例:I am Chinese student and I am studying in Henan University of Technology 输出样例: 1 2 am 2 Chinese 1 student 1 and 1 studying 1 in 1 Henan 1 University 1 of 1 Technology 1
可以使用 Python 中的字典类型来保存单词及其频次。具体实现如下:
```python
sentence = input("请输入一个英文句子或单词组成的字符串:")
words = sentence.split() # 将句子按空格分割成单词列表
word_count = {} # 创建空字典用于保存单词及其频次
for word in words:
if word in word_count:
word_count[word] += 1 # 如果单词已经在字典中,频次加 1
else:
word_count[word] = 1 # 如果单词不在字典中,添加到字典中,频次为 1
# 输出单词及其频次
for word, count in word_count.items():
print(word, count)
```
输出结果如下:
```
请输入一个英文句子或单词组成的字符串:I am Chinese student and I am studying in Henan University of Technology
I 1
am 2
Chinese 1
student 1
and 1
studying 1
in 1
Henan 1
University 1
of 1
Technology 1
```