Python如何筛选词频字典中出现次数不低于指定阈值n的条目
从词频字典中筛选符合最低出现次数的词条
需求说明
- 现有存储了词汇及其对应语料库中出现次数的Python字典,需要筛选出出现次数不低于n次的词汇,本次示例中n取值为10
- 筛选后返回的新字典需保留原字典的条目顺序,包含从第一个条目到
astatine为止的所有符合条件的键值对
示例输入字典
dictionary = { 'beryllium': 60, 'inch': 56, 'any': 51, 'such': 31, 'court': 26, 'be': 25, 'by': 23, 'arsenic': 21, 'person': 20, 'land': 20, 'Lapp': 16, 'county': 15, 'Associate_in_Nursing': 15, 'executor': 15, 'information_technology': 14, 'state': 14, 'angstrom': 14, 'not': 14, 'other': 14, 'boundary': 14, 'tree': 13, 'administrator': 12, 'are': 11, 'helium': 11, 'no': 11, 'action': 10, 'rich_person': 10, 'use': 10, 'astatine': 10, 'being': 9, 'tobacco': 9, 'every': 9, 'curse': 9, 'ordain': 8, 'justice': 8, 'one': 8, 'notice': 8, 'law': 8, 'pound': 8, 'debt': 8, 'creditor': 8 }
实现代码(Python 3.7+,默认支持字典保留插入顺序)
n = 10 filtered_dict = {} for key, value in dictionary.items(): if value >= n: filtered_dict[key] = value # 遍历到astatine即终止,满足要求的范围条件 if key == 'astatine': break
如果仅需要筛选所有出现次数不低于n的词条,无需限制到astatine停止,可以直接使用更简洁的字典推导式:
n = 10 filtered_dict = {k:v for k,v in dictionary.items() if v >=n}
示例输出结果
{ 'beryllium': 60, 'inch': 56, 'any': 51, 'such': 31, 'court': 26, 'be': 25, 'by': 23, 'arsenic': 21, 'person': 20, 'land': 20, 'Lapp': 16, 'county': 15, 'Associate_in_Nursing': 15, 'executor': 15, 'information_technology': 14, 'state': 14, 'angstrom': 14, 'not': 14, 'other': 14, 'boundary': 14, 'tree': 13, 'administrator': 12, 'are': 11, 'helium': 11, 'no': 11, 'action': 10, 'rich_person': 10, 'use': 10, 'astatine': 10 }
内容的提问来源于stack exchange,提问作者krasnapolsky
相关产品推荐
相关产品推荐

