如何用Python统计单词中指定字母数并找出含该字母最多的单词
Python统计单词中特定字母数量并找出含该字母最多的单词
原代码存在的问题
- 变量拼写错误:
couner += 1应为counter += 1,导致统计计数无法正确累加 - 逻辑判断错误:
if counter < maximal会更新计数更小的单词,应该改为counter > maximal才能追踪含'i'最多的单词 - 冗余判断:
e.__contains__("i")没必要,直接统计字母数量即可,不含该字母的单词计数自然为0 - 统计方式繁琐:手动遍历字符统计可以用字符串内置方法简化
修正基础错误后的代码
word_list = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup'] def find_most_target_char(word_list, target_char='i'): max_count = 0 result_word = "" for word in word_list: current_count = 0 # 手动遍历字符统计(保留原逻辑修正错误) for char in word: if char == target_char: current_count += 1 # 更新最大计数对应的单词 if current_count > max_count: max_count = current_count result_word = word return result_word, max_count word, count = find_most_target_char(word_list) print(f"含字母'i'最多的单词是:{word},共出现{count}次")
优化后的简洁版本(利用字符串count方法)
Python字符串内置的count()方法可以直接统计指定字符的出现次数,无需手动遍历:
word_list = ['box', 'computer', 'sheep', 'family', 'illegal', 'bubble', 'lamp', 'circuit', 'building', 'plant', 'these', 'cup'] def find_most_target_char(word_list, target_char='i'): max_count = -1 result_word = "" for word in word_list: current_count = word.count(target_char) if current_count > max_count: max_count = current_count result_word = word return result_word, max_count word, count = find_most_target_char(word_list) print(f"含字母'i'最多的单词是:{word},共出现{count}次")
运行结果
上述代码运行后会输出:含字母'i'最多的单词是:building,共出现3次
内容的提问来源于stack exchange,提问作者cofee_and_coding
相关产品推荐
相关产品推荐

