使用Python计算字符串数组在文本中出现的次数可以通过以下步骤实现:
import re
text = "This is a sample text. It contains some sample sentences."
words = ["sample", "text", "sentences"]
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
occurrences = count_occurrences(text, words)
for word, count in occurrences.items():
print(f"The word '{word}' appears {count} times.")
这段代码使用正则表达式匹配每个字符串数组中的单词,并计算其在文本中出现的次数。最后,输出每个单词的出现次数。
请注意,答案中没有提及特定的云计算品牌商,因此无需给出相关产品和产品介绍链接地址。
领取专属 10元无门槛券
手把手带您无忧上云