
在数据分析和自然语言处理(nlp)领域,我们经常需要从大量的文本数据中提取有意义的信息。一个常见的需求是识别文本内容所属的预定义类别,例如根据文本中出现的关键词来判断文章的主题。本教程将聚焦于一个具体的场景:给定一个包含文本内容的pandas dataframe,以及多组关键词列表(代表不同的类别),我们需要计算每行文本中每个关键词类别的“出现概率”,并最终为每行文本标记出具有最高概率的关键词类别。这里定义的“概率”是:特定关键词类别中关键词的总出现次数除以该行文本的总词数。此外,我们还将处理关键词变体(如“lichies”应计入“lichi”)以及文本中未出现任何预设关键词的情况。
首先,我们创建一个示例Pandas DataFrame和用于分类的关键词列表。这些关键词列表将以字典的形式组织,键为类别名称,值为该类别的关键词列表。
import pandas as pd
import re
from collections import Counter
# 示例DataFrame
data = {
'content': [
'My favorite fruit is mango. I like lichies too. I live in au. Cows are domistic animals.',
'I own RTX 4090...',
'There is political colfict between us and ca.',
'au, br mango, lichi apple,.... \n cat, cow, monkey donkey dogs'
]
}
df = pd.DataFrame(data)
# 定义关键词类别
labels = {
'fruits': ['mango', 'apple', 'lichi'],
'animals': ['dog', 'cat', 'cow', 'monkey'],
'country': ['us', 'ca', 'au', 'br'],
}
print("原始DataFrame:")
print(df)要实现上述目标,我们需要解决以下几个关键问题:
我们将创建一个自定义函数 calculate_probability,然后使用Pandas的 .apply() 方法将其应用到DataFrame的 content 列上。
该函数将接收一行文本内容和关键词类别字典作为输入,并返回该行文本的最高概率标签。
def calculate_probability(text, labels_dict):
"""
计算文本中各关键词类别的概率,并返回最高概率的类别标签。
参数:
text (str): 输入的文本内容。
labels_dict (dict): 关键词类别字典,键为类别名,值为关键词列表。
返回:
str: 具有最高概率的类别标签,如果所有概率均为0则返回 'NaN'。
"""
# 1. 文本分词与小写化
# 使用正则表达式匹配单词边界,提取所有单词并转换为小写。
# 这有助于处理标点符号并实现大小写不敏感的匹配。
words = re.findall(r'\b\w+\b', text.lower())
word_count = len(words)
# 如果文本中没有单词,则无法计算概率,直接返回 'NaN'
if word_count == 0:
return 'NaN'
probs = {}
# 2. 遍历每个关键词类别,进行模糊匹配与计数
for label_name, keyword_list in labels_dict.items():
keyword_matches_count = 0
# 遍历文本中的每个单词
for text_word in words:
# 遍历当前类别的每个关键词
for keyword in keyword_list:
# 模糊匹配:如果文本中的单词包含(作为子串)任一关键词
# 例如:'lichies' 包含 'lichi','dogs' 包含 'dog'
if keyword in text_word:
keyword_matches_count += 1
break # 找到一个匹配后,当前 text_word 不再与其他关键词比较,避免重复计数
# 3. 概率计算
probs[label_name] = keyword_matches_count / word_count
# 4. 找出最高概率的标签
# 使用 max() 函数和 key 参数,根据字典值(概率)找到对应的键(标签)
max_label = max(probs, key=probs.get)
# 5. 处理所有概率均为0的情况
# 如果最高概率值大于0,则返回该标签;否则,表示没有匹配到任何关键词,返回 'NaN'
if probs[max_label] > 0:
return max_label
else:
return 'NaN'
现在,我们可以使用Pandas的 .apply() 方法将 calculate_probability 函数应用到 df['content'] 列上,创建新的 label 列。请注意,.apply() 在应用于 Series 时,函数默认接收 Series 中的每个元素作为第一个参数。其他参数可以通过 **kwargs 传递。
# 将函数应用到DataFrame的 'content' 列
# labels=labels 是将我们定义的关键词类别字典作为额外参数传递给函数
df['label'] = df['content'].apply(calculate_probability, labels_dict=labels)
print("\n处理后的DataFrame:")
print(df)import pandas as pd
import re
from collections import Counter
# 示例DataFrame
data = {
'content': [
'My favorite fruit is mango. I like lichies too. I live in au. Cows are domistic animals.',
'I own RTX 4090...',
'There is political colfict between us and ca.',
'au, br mango, lichi apple,.... \n cat, cow, monkey donkey dogs'
]
}
df = pd.DataFrame(data)
# 定义关键词类别
labels = {
'fruits': ['mango', 'apple', 'lichi'],
'animals': ['dog', 'cat', 'cow', 'monkey'],
'country': ['us', 'ca', 'au', 'br'],
}
def calculate_probability(text, labels_dict):
"""
计算文本中各关键词类别的概率,并返回最高概率的类别标签。
参数:
text (str): 输入的文本内容。
labels_dict (dict): 关键词类别字典,键为类别名,值为关键词列表。
返回:
str: 具有最高概率的类别标签,如果所有概率均为0则返回 'NaN'。
"""
words = re.findall(r'\b\w+\b', text.lower())
word_count = len(words)
if word_count == 0:
return 'NaN'
probs = {}
for label_name, keyword_list in labels_dict.items():
keyword_matches_count = 0
for text_word in words:
for keyword in keyword_list:
# 模糊匹配:如果文本中的单词包含(作为子串)任一关键词
if keyword in text_word:
keyword_matches_count += 1
break
probs[label_name] = keyword_matches_count / word_count
max_label = max(probs, key=probs.get)
if probs[max_label] > 0:
return max_label
else:
return 'NaN'
# 应用函数
df['label'] = df['content'].apply(calculate_probability, labels_dict=labels)
print("最终结果:")
print(df)运行上述代码,您将得到如下输出:
content label 0 My favorite fruit is mango. I like lichies too... fruits 1 I own RTX 4090... NaN 2 There is political colfict between us and ca. country 3 au, br mango, lichi apple,.... \n cat, cow, mo... animals
注意: 示例输出中 content 4 的 label 为 animals,这与问题描述中 P(fruits) = 3/10, P(animals) = 4/10, P(country)=2/10 Highest Probability: animals 相符,表明我们的模糊匹配逻辑
以上就是Pandas文本列关键词类别概率计算及最高概率标签提取教程的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号