统计一个单词在一句话里出现的字数
时间: 2023-12-09 16:03:58 浏览: 40
您好!感谢您对ChitGPT的使用。针对您的问题,我可以提供以下代码实现:
```python
def count_word(sentence, word):
"""
统计一个单词在一句话里出现的次数
:param sentence: 句子
:param word: 待统计的单词
:return: 单词在句子中的出现次数
"""
# 将句子中的所有单词转为小写,以便于匹配
sentence = sentence.lower()
word = word.lower()
# 将句子按照空格分割成单词列表
words = sentence.split()
# 统计单词出现次数
count = 0
for w in words:
if w == word:
count += 1
return count
```
使用方法:
```python
sentence = "This is a sample sentence that contains the word sample multiple times."
word = "sample"
count = count_word(sentence, word)
print(f"The word '{word}' appears {count} times in the sentence.")
```
输出结果:
```
The word 'sample' appears 2 times in the sentence.
```
希望能帮到您!如果还有其他问题,欢迎随时提问。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)