编写返回字符串中各单词长度的Python代码相关咨询
优化你的单词长度统计代码
嘿,我仔细看了你的代码,它确实能完成“返回字符串中每个单词长度”的需求,但在标点处理逻辑上存在小bug,同时我们可以让代码更简洁易读。先贴出你的原代码方便对比:
def word_lengths(a): a = a.lower() c = list(a) a = "" for x in c: if x == "," or x == "." or x == "'" or x == "!" or x == "?": c[c.index(x)] = "" for x in c: a += x y = a.split() z = {} for x in y: z[x] = len(x) return z print(word_lengths("I ate a bowl of cereal out of a dog bowl today."))
原代码的问题
你的核心思路是对的:转小写→清理标点→分割单词→生成长度字典。但标点处理部分有个隐藏bug:当字符串里有重复的标点时(比如"Hi, there, how's it going?"),c.index(x)只会返回第一个匹配标点的索引,当你把第一个标点置为空后,后续遇到相同标点时,c.index(x)会找不到该字符,直接抛出ValueError。
优化后的代码方案
这里提供两种更简洁且无bug的写法:
方案1:用str.translate快速清理标点
这个方法利用Python字符串的内置方法,一次性移除所有指定标点,效率很高:
def word_lengths(s): # 定义需要移除的标点集合 punctuation = ',\'.!?' # 创建标点到空字符的转换表 trans_table = str.maketrans('', '', punctuation) # 清理标点、转小写、分割单词 words = s.lower().translate(trans_table).split() # 用字典推导式生成结果 return {word: len(word) for word in words} print(word_lengths("I ate a bowl of cereal out of a dog bowl today."))
方案2:逐个字符过滤(更直观)
如果你偏好更直白的逻辑,可以直接遍历每个字符,只保留非标点的内容:
def word_lengths(a): cleaned_chars = [] # 遍历转小写后的每个字符 for char in a.lower(): # 如果字符不是标点,就保留 if char not in ',\'.!?': cleaned_chars.append(char) # 拼接成清理后的字符串,再分割成单词 cleaned_str = ''.join(cleaned_chars) words = cleaned_str.split() # 生成单词-长度字典 return {word: len(word) for word in words} print(word_lengths("I ate a bowl of cereal out of a dog bowl today."))
额外小优化
原代码里手动创建空字典z = {}再逐个赋值,换成字典推导式会更简洁,这也是上面优化方案里用到的写法,既清晰又符合Pythonic风格。
内容的提问来源于stack exchange,提问作者user9660128
相关产品推荐
相关产品推荐

