如何统计指定词表在数据集观测文本中的出现次数(含小写/标点处理)
错误原因
Python的str.count()方法仅支持传入1个待匹配的子串参数,你一次性传入10个词汇不符合语法要求,因此触发了参数数量不匹配的报错。
可行实现方案
实现逻辑:先将目标词表转为集合提升查找效率,再对每条文本统一做转小写、去标点的清洗操作,最后逐词判断是否属于目标词表累加计数即可。
import string # 目标词表转集合,去重同时将查找效率提升至O(1) target_words = set(['model','language','models','task', 'data', 'paper', 'results', 'information', 'text','performance']) # 观测数据集示例 column = ['The models are showing a great performance.', 'The information and therefor the data in the text are good enough to fulfill the task.', 'Data in this way results in the best information and thus performance.'] count_list = [] # 生成标点删除映射表,高效去除所有标点符号 punc_remove_table = str.maketrans('', '', string.punctuation) for sentence in column: # 先转小写,再删除所有标点 clean_sentence = sentence.lower().translate(punc_remove_table) current_count = 0 for word in clean_sentence.split(): if word in target_words: current_count += 1 count_list.append(current_count) # 转换为要求的元组输出格式 output = tuple(count_list) print(output)
运行后输出结果为(2, 4, 4),完全符合预期要求。
内容的提问来源于stack exchange,提问作者Paul Engelbert
相关产品推荐
相关产品推荐

