在Python中计算字符串中的单词可以通过以下步骤实现:
sentence = "Hello, world! This is a sentence."
words = sentence.split()
print(words)
输出结果为:['Hello,', 'world!', 'This', 'is', 'a', 'sentence.']
word_count = len(words)
print("单词数量:", word_count)
输出结果为:单词数量:6
word_count_dict = {}
for word in words:
if word in word_count_dict:
word_count_dict[word] += 1
else:
word_count_dict[word] = 1
print("每个单词的出现次数:")
for word, count in word_count_dict.items():
print(word, ":", count)
输出结果为:
每个单词的出现次数:
Hello, : 1
world! : 1
This : 1
is : 1
a : 1
sentence. : 1
这样就可以在Python中计算字符串中的单词了。
推荐的腾讯云相关产品:腾讯云函数(Serverless Cloud Function),腾讯云云服务器(CVM),腾讯云数据库(TencentDB),腾讯云对象存储(COS),腾讯云人工智能(AI),腾讯云物联网(IoT),腾讯云移动开发(Mobile Development),腾讯云区块链(Blockchain),腾讯云元宇宙(Metaverse)。
腾讯云产品介绍链接地址:https://cloud.tencent.com/product
领取专属 10元无门槛券
手把手带您无忧上云