修改Python单词统计代码:实现回文单词按出现次数2倍计数
解决方案
以下是修改后的代码,实现了回文单词按出现次数2倍计数的需求:
text = input("输入文本:") text = text.lower() # 移除文本中的标点符号 punctuations = ".!,?" for p in punctuations: text = text.replace(p, "") lst_text = text.split() quantity = int(input("要查找多少个单词: ")) word_for_find = [] for _ in range(quantity): temp = input("输入单词: ") temp = temp.lower() word_for_find.append(temp) word_counter = 0 def is_palindrome(word): # 判断单词是否为回文(正读反读一致) return word == word[::-1] for word in lst_text: for target in word_for_find: if word == target: # 回文单词计数加倍,普通单词正常计数 word_counter += 2 if is_palindrome(target) else 1 print(word_counter)
关键改动说明
- 新增
is_palindrome函数:通过对比单词与其反转字符串,快速判断是否为回文 - 调整计数逻辑:匹配目标单词时,根据是否为回文决定累加2还是1
- 优化标点处理:用简洁的循环批量移除指定标点符号
- 适配中文输入提示,提升使用体验
测试示例
输入文本:Kids love doing gag. Gag is good.
要查找多少个单词: 2
输入单词: kids
输入单词: gag
输出结果:5
计算逻辑:kids非回文,出现1次计1;gag是回文,出现2次计2×2=4,总和1+4=5,符合需求。
内容的提问来源于stack exchange,提问作者Gabe Newal
相关产品推荐
相关产品推荐

