首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何用Python计算字符串数组在文本中出现的次数?

使用Python计算字符串数组在文本中出现的次数可以通过以下步骤实现:

  1. 导入所需的模块:
代码语言:txt
复制
import re
  1. 定义文本字符串和字符串数组:
代码语言:txt
复制
text = "This is a sample text. It contains some sample sentences."
words = ["sample", "text", "sentences"]
  1. 定义一个函数来计算字符串数组中每个字符串在文本中出现的次数:
代码语言:txt
复制
def count_occurrences(text, words):
    count = {}
    for word in words:
        pattern = r'\b' + re.escape(word) + r'\b'
        matches = re.findall(pattern, text, re.IGNORECASE)
        count[word] = len(matches)
    return count
  1. 调用函数并输出结果:
代码语言:txt
复制
occurrences = count_occurrences(text, words)
for word, count in occurrences.items():
    print(f"The word '{word}' appears {count} times.")

这段代码使用正则表达式匹配每个字符串数组中的单词,并计算其在文本中出现的次数。最后,输出每个单词的出现次数。

请注意,答案中没有提及特定的云计算品牌商,因此无需给出相关产品和产品介绍链接地址。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券