Python中含标点字符串单词交换函数的问题及解决需求
解决Python字符串单词交换的两个核心问题:标点匹配与参数校验
一、标点符号处理问题的修复
你的代码用split()拆分字符串后,单词会附带前后标点(比如specialist,、(software),直接和目标单词specialist、software对比肯定匹配不上,自然没法完成替换。
解决思路:先提取每个单词的纯词干(去掉前后所有标点),用纯词干和目标单词匹配;匹配成功后,保留原单词的标点格式——也就是把原单词的前缀标点、后缀标点分别加在替换后的单词前后。
具体实现可以用word.strip(punctuation)获取纯词干,用word[:len(word)-len(stem)]提取前缀标点,word[len(stem):]提取后缀标点。
二、参数校验问题的修复
要实现「传入不存在的单词就报错」的需求,你需要先收集字符串里所有的纯词干,检查word_1和word_2是否都在这个集合里。如果有任何一个不在,直接抛出ValueError。
修正后的完整代码
from string import punctuation def swap_words(user_string, word_1, word_2): """Function for swapping words in string""" print(f"\nSentence before changing: {user_string}") listed_string = user_string.split() # 收集所有纯词干,用于参数校验 word_stems = [word.strip(punctuation) for word in listed_string] if word_1 not in word_stems or word_2 not in word_stems: raise ValueError(f"单词 '{word_1}' 或 '{word_2}' 在字符串中不存在") for i, word in enumerate(listed_string): stem = word.strip(punctuation) # 提取原单词的前后标点 prefix = word[:len(word)-len(stem)] if len(word) > len(stem) else "" suffix = word[len(stem):] if len(word) > len(stem) else "" if stem == word_1: listed_string[i] = prefix + word_2 + suffix elif stem == word_2: listed_string[i] = prefix + word_1 + suffix changed_string = ' '.join(listed_string) print(f"Changed sentence: {changed_string}") sentence = "A programmer is a specialist, who develops software (in simpler " \ "cases, individual programs) for programmable devices." # 测试正常交换 swap_words(sentence, 'specialist', 'software') # 测试传入不存在的单词(会抛出错误) # swap_words(sentence, 'specialist', 'invalid_word')
代码说明
- 标点处理:不管单词是带前标点(如
(software)、后标点(如specialist,)还是前后都带,都能正确提取纯词干并保留原标点格式,替换后不会破坏原句子的标点布局。 - 参数校验:在遍历替换前先做检查,确保两个目标单词都存在,不存在则直接抛出明确的错误信息,符合预期的报错逻辑。
内容的提问来源于stack exchange,提问作者Tsunami
相关产品推荐
相关产品推荐

