|
发表于 2023-7-1 09:31:45
|
显示全部楼层
要进行多个单词的词频统计,您可以使用Python中的字符串处理和计数功能来实现。下面是一个示例代码,使用Python中的Counter类来实现多个单词的词频统计:
- from collections import Counter
- def word_frequency(text, words):
- # 将文本中的标点符号替换为空格
- text = text.replace(",", " ").replace(".", " ").replace("!", " ").replace("?", " ").replace(";", " ")
- # 将文本拆分为单词列表
- word_list = text.split()
- # 统计单词出现的频率
- word_counts = Counter(word_list)
- # 提取指定单词的词频统计结果
- result = {word: word_counts[word] for word in words}
- return result
- # 示例文本
- text = "Climate change is a serious issue. Climate action is needed to mitigate its effects."
- # 指定需要统计的单词列表
- words = ["climate", "change", "action"]
- # 进行词频统计
- frequency_result = word_frequency(text.lower(), words)
- # 打印结果
- for word, count in frequency_result.items():
- print(f"Word: {word}, Count: {count}")
复制代码
在上述示例中,我们定义了一个word_frequency()函数,它接受一个文本内容和一个需要统计的单词列表作为参数。首先,我们通过替换标点符号,并将文本拆分为单词列表。然后,我们使用Counter类来统计每个单词出现的次数,并将结果存储在一个字典中。最后,我们提取指定单词的词频统计结果,并打印出来。
请注意,示例代码中将文本转换为小写字母以进行不区分大小写的统计。如果您希望区分大小写,请将text.lower()改为text。
希望这可以帮助到您!如果您有任何其他问题,请随时向我提问。 |
|