Google Colab下Python3复数转换UDF调试:函数返回空字典异常
复数变形函数问题排查与修复方案
核心故障原因
- return 语句缩进错误:这是导致后续逻辑完全不执行的核心问题。原代码中第一个空字符串判断的return语句没有缩进在if分支内部,而是与if同级,导致只要执行完第一个判断,无论输入是否为空,都会直接返回字典,后续所有判断逻辑属于永远不会触发的死代码。
- 未按需求实现普通词汇的复数变形规则,仅完成了三类特殊场景的判断框架。
- 每次调用函数都会重复读取proper_noun.txt文件,存在不必要的IO开销。
修复后完整代码
# 预先加载专有名词列表,仅执行一次 filepath = '/proper_noun.txt' with open(filepath, 'r', encoding='utf-8') as f: proper_nouns = [line.strip() for line in f if line.strip()] # 过滤空行避免无效匹配 def pluralize(word): # 初始化返回字典 dictionary = {'plural': '', 'status': ''} # 空字符串判断 if word == '': dictionary['plural'] = '' dictionary['status'] = 'empty_string' return dictionary # 以s结尾/已为复数判断 if word[-1] == 's': dictionary['plural'] = word dictionary['status'] = 'already_in_plural' return dictionary # 专有名词判断 if word in proper_nouns: dictionary['plural'] = word dictionary['status'] = 'proper_noun' return dictionary # 普通词汇变形逻辑 vowels = {'a', 'e', 'i', 'o', 'u'} # 辅音+y结尾规则 if word[-1] == 'y' and word[-2] not in vowels: plural = word[:-1] + 'ies' # f结尾规则 elif word[-1] == 'f': plural = word[:-1] + 'ves' # sh/ch/z结尾规则 elif word.endswith(('sh', 'ch', 'z')): plural = word + 'es' # 无匹配规则默认加s else: plural = word + 's' dictionary['plural'] = plural dictionary['status'] = 'success' return dictionary
修复说明
- 所有
return语句均缩进对应到所属if分支内部,避免提前触发返回 - 专有名词列表使用
with open语句读取,自动处理文件关闭,且仅在函数初始化时执行一次,减少重复IO开销 - 读取文件时过滤空行,避免无关空字符串进入专有名词匹配列表
- 严格按照给定规则实现普通词汇的三类变形逻辑,无匹配规则时默认添加
s - 若需要适配大小写不敏感的专有名词匹配,可将判断逻辑修改为
word.capitalize() in proper_nouns,或统一存储/匹配规则大小写即可
内容的提问来源于stack exchange,提问作者user14519115
相关产品推荐
相关产品推荐

