技术求助:编写含标点最多单词提取及标点移除程序并修正代码
问题1:返回字符串中包含标点符号最多的单词
你的第一段代码逻辑是累加数字并记录最大值,和统计单词标点数量的需求完全不相关。以下是正确实现:
借助Python内置的string模块获取所有标点符号,将输入字符串分割为单词后,逐个统计每个单词里的标点数量,最终找出标点最多的单词。
import string def get_punctuation_richest_word(s): # 按空格分割字符串为单词,可根据实际需求调整分割规则 words = s.split() max_punct_count = -1 target_word = "" for word in words: # 统计当前单词的标点数量 punct_count = sum(1 for char in word if char in string.punctuation) if punct_count > max_punct_count: max_punct_count = punct_count target_word = word # 若所有单词无标点,返回空字符串或第一个单词,可按需调整 return target_word if max_punct_count != -1 else ""
问题2:移除字符串中所有标点符号
你的第二段代码是把数字替换成*,和移除标点的需求不符。正确实现如下:
利用string.punctuation匹配所有标点,遍历字符串时只保留非标点字符。
import string def remove_all_punctuation(s): result = "" for char in s: if char not in string.punctuation: result += char return result # 也可以用更简洁的生成器表达式写法 def remove_all_punctuation(s): return ''.join(char for char in s if char not in string.punctuation)
内容的提问来源于stack exchange,提问作者keith
相关产品推荐
相关产品推荐

