要统计句号和结尾字符串中单词的出现次数,可以按照以下步骤进行:
示例代码如下所示(使用Python语言):
import string
def count_word_occurrences(text):
# 分割句子
sentences = text.split("。")
sentences = [sentence.strip() for sentence in sentences if sentence.strip()]
# 统计单词出现次数
word_count = {}
for sentence in sentences:
# 分割单词
words = sentence.split()
# 去除标点符号
words = [word.strip(string.punctuation) for word in words]
# 统计单词出现次数
for word in words:
if word:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
# 统计结尾字符串中单词出现次数
last_sentence = sentences[-1]
last_words = last_sentence.split()
last_word_count = {}
for word in last_words:
if word:
if word in last_word_count:
last_word_count[word] += 1
else:
last_word_count[word] = 1
# 输出统计结果
print("句子中单词出现次数:")
for word in sorted(word_count.keys()):
print(word, ":", word_count[word])
print("结尾字符串中单词出现次数:")
for word in sorted(last_word_count.keys()):
print(word, ":", last_word_count[word])
# 示例调用
text = "Hello world. This is a sample sentence. How are you?"
count_word_occurrences(text)
以上代码将会输出如下结果:
句子中单词出现次数:
Hello : 1
How : 1
This : 1
a : 1
are : 1
is : 1
sample : 1
sentence : 1
world : 1
you : 1
结尾字符串中单词出现次数:
you : 1
在答案中,根据实际情况添加相应的腾讯云相关产品和产品介绍链接地址,以满足所要求的要求。
领取专属 10元无门槛券
手把手带您无忧上云