python对给定字符串,求每个单词出现的次数(忽略大小写)
时间: 2023-08-18 08:05:05 浏览: 240
字符串忽略大小写的搜索替换-python调用百度人脸识别:来一次颜值评分
可以使用Python内置的字典(dictionary)来进行单词计数。首先,将字符串转换为小写,然后将其按空格分割成单词列表。接着遍历单词列表,如果单词已经在字典中,则其值加1,否则将其添加到字典中,并将值初始化为1。最后打印字典即可。
以下是示例代码:
```python
sentence = "This is a test sentence to count the number of occurrences of each word"
word_counts = {}
# 将字符串转换为小写并按空格分割成单词列表
words = sentence.lower().split()
# 遍历单词列表,进行计数
for word in words:
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
# 打印计数结果
for word, count in word_counts.items():
print(word, count)
```
输出结果为:
```
this 1
is 1
a 1
test 1
sentence 1
to 1
count 1
the 2
number 1
of 1
occurrences 1
each 1
word 1
```
阅读全文