python对给定字符串,求每个单词出现的次数(忽略大小写)
时间: 2023-08-18 19:05:05 浏览: 141
可以使用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
```
相关问题
编写函数 统计给定字符串中各个字母出现的次数 不区分大小写
可以使用Python内置的字典类型来统计每个字母出现的次数。具体实现如下:
```python
def count_letters(s):
# 将字符串转换为小写,方便统计
s = s.lower()
# 定义一个空字典,用于统计每个字母出现的次数
letter_counts = {}
# 遍历字符串中的每个字符
for c in s:
# 如果是字母,则更新字典中对应字母的计数
if c.isalpha():
letter_counts[c] = letter_counts.get(c, 0) + 1
# 返回字典
return letter_counts
```
这个函数接受一个字符串作为输入,返回一个字典,其中键为每个出现过的字母(不区分大小写),值为该字母在字符串中出现的次数。可以通过以下方式调用该函数:
```python
s = "Hello, World!"
counts = count_letters(s)
print(counts)
```
输出结果为:
```
{'h': 1, 'e': 1, 'l': 3, 'o': 2, 'w': 1, 'r': 1, 'd': 1}
```
表示在字符串中,字母'h'出现了一次,字母'e'出现了一次,字母'l'出现了三次,以此类推。
python给定某一字符串s,对其中的每一字符c进行大小写转换
可以使用s.upper()和s.lower()方法来实现大小写转换,具体代码如下:
s = "Hello World"
result = ""
for c in s:
if c.isupper():
result += c.lower()
else:
result += c.upper()
print(result)
输出结果为:
hELLO wORLD