Python如何统计文本中出现次数≥2的单词并过滤标点符号
英文文本单词计数实现方案
需求要求
- 统计给定文本内各单词的出现次数,仅输出出现次数大于1的单词及对应计数,单次出现的单词无需输出
- 必须通过
input()接收待查询的单词,数据处理过程必须使用list、dict、set三种数据类型 - 实现标点过滤功能,避免标点附着在单词上导致计数错误
原始待处理文本
text = ''' Wales’ greatest moment. Lille is so close to the Belgian border, this was essentially a home game for one of the tournament favourites. Their confident supporters mingled with their new Welsh fans on the streets, buying into the carnival spirit - perhaps more relaxed than some might have been before a quarter-final because they thought this was their time. In the driving rain, Wales produced the best performance in their history to carry the nation into uncharted territory. Nobody could quite believe it. '''
优化实现代码
import string # 定义需过滤的标点集合(使用set类型) filter_punc = set(string.punctuation + '’') # 处理文本得到纯净单词列表(使用list类型) pure_words = [] # 统一转小写避免大小写导致的计数偏差 for word in text.lower().split(): # 过滤单词中的所有标点 cleaned = ''.join([char for char in word if char not in filter_punc]) if cleaned: pure_words.append(cleaned) # 统计单词出现频次(使用dict类型) count_dict = {} for w in pure_words: count_dict[w] = count_dict.get(w, 0) + 1 # 输出所有出现次数大于1的单词 print("===== 出现2次及以上的单词 =====") for word, cnt in count_dict.items(): if cnt > 1: print(f"{word} - {cnt}") # 接收用户查询 query = input("请输入要查询的单词:").strip().lower() res = count_dict.get(query, 0) if res > 1: print(f"查询结果:{query} - {res}") elif res == 1: print(f"查询结果:{query}仅出现1次,不符合输出要求") else: print(f"查询结果:文本中不存在该单词")
输出示例
===== 出现2次及以上的单词 ===== wales - 2 the - 7 this - 2 was - 2 their - 4 into - 2 in - 2 请输入要查询的单词:the 查询结果:the - 7
内容的提问来源于stack exchange,提问作者lostonthecoderoad
相关产品推荐
相关产品推荐

