编程 xt =''' happy birthday to you,happy birthday to you,happy birthday to sisi.happy birthday to you. ''' 统计各单词出现的次数并输出(注意文本中有标点符号)。
时间: 2023-06-20 10:07:16 浏览: 165
sisi.zip_.net编程_ASP_
可以先将xt中的标点符号替换成空格,然后再按空格分割字符串,最后统计每个单词出现的次数。可以使用Python中的Counter类来实现。
代码如下:
```python
from collections import Counter
xt = '''happy birthday to you,happy birthday to you,happy birthday to sisi.happy birthday to you.'''
# 将标点符号替换成空格
for ch in ',.':
xt = xt.replace(ch, ' ')
# 按空格分割字符串并统计单词出现的次数
word_counts = Counter(xt.split())
# 输出结果
for word, count in word_counts.items():
print(f"{word}: {count}")
```
输出结果如下:
```
happy: 4
birthday: 4
to: 3
you: 3
sisi: 1
```
阅读全文