如何用Python筛选DataFrame中与关键词同句的用户名
问题描述
现有如下结构的DataFrame df:
df = index Text ---------------- 0 My name is George and I don't like football 1 Hey find me on instagram to play basketball 2 I am down for Saturday night ... 1000 text1000
另有关键词列表:
key_word = ['football', 'basketball', 'tennis']
以及用户名列表:
usernames = ['instagram', 'facebook', 'snapchat']
需求:找出DataFrame中与关键词出现在同一条文本内的用户名,示例输出为:
output = ['instagram']
解决方案
可以用Python结合Pandas实现,具体步骤:
- 定义一个函数,用于检查单条文本是否同时包含关键词和用户名,并提取匹配的用户名:
def find_matching_usernames(text): # 统一转小写,避免大小写导致的匹配遗漏 lower_text = text.lower() # 先判断文本是否包含至少一个关键词 has_keyword = any(word in lower_text for word in key_word) if not has_keyword: return [] # 提取该文本中存在的用户名 matched_users = [user for user in usernames if user in lower_text] return matched_users
- 对DataFrame的
Text列批量应用上述函数,收集所有匹配结果并去重:
# 应用函数并展开所有匹配的用户名 all_matches = df['Text'].apply(find_matching_usernames).explode() # 去除空值、去重后转为列表 output = all_matches.dropna().unique().tolist()
运行以上代码后,即可得到符合需求的用户名列表,例如示例中的['instagram']。
内容的提问来源于stack exchange,提问作者John Angelopoulos
相关产品推荐
相关产品推荐

