Python如何判断两个及以上字符串是否拥有指定数量的共同单词
Python实现字符串共同单词检测
实现逻辑
- 先清洗输入字符串:剔除所有标点符号,拆分出独立单词
- 单词匹配不区分大小写,同时支持保留原单词的书写格式
- 求多个字符串的单词交集,判断长度是否≥3后输出结果
双字符串匹配代码
import string def get_common_words(str1, str2): # 字符串清洗处理:返回{小写单词: 原格式单词}映射 def process_string(s): # 去除所有标点 remove_punct = str.maketrans('', '', string.punctuation) cleaned_s = s.translate(remove_punct) word_list = cleaned_s.split() return {word.lower(): word for word in word_list} words_map1 = process_string(str1) words_map2 = process_string(str2) # 取共同单词的小写key common_lower_keys = words_map1.keys() & words_map2.keys() # 按第一个字符串的出现顺序返回原格式共同单词 common_words = [word for word in words_map1.values() if word.lower() in common_lower_keys] return common_words # 示例测试 string1 = "Password age (minimum) is set to 60" string2 = "age of password is set to 60 or less!" common_words = get_common_words(string1, string2) if len(common_words) >= 3: print("string1 & string2 have 3 or more words in common:\n") print(common_words) else: print("string1 & string2 have less than 3 words in common")
运行后输出结果和要求一致:
string1 & string2 have 3 or more words in common: ['Password', 'age', 'is', 'set', 'to', '60']
多字符串批量匹配拓展
如果需要同时匹配N个字符串的共同单词,可以用以下版本:
import string from functools import reduce def get_multi_str_common(str_list): def process_string(s): remove_punct = str.maketrans('', '', string.punctuation) cleaned_s = s.translate(remove_punct) word_list = cleaned_s.split() return {word.lower(): word for word in word_list} processed_maps = [process_string(s) for s in str_list] # 求所有字符串的共同单词key common_keys = reduce(lambda a, b: a.keys() & b.keys(), processed_maps) common_words = [word for word in processed_maps[0].values() if word.lower() in common_keys] return common_words # 多字符串测试 test_strs = [ "Password age (minimum) is set to 60", "age of password is set to 60 or less!", "your password age should be set to 60" ] common = get_multi_str_common(test_strs) if len(common) >= 3: print(f"所有输入字符串共有{len(common)}个共同单词,满足≥3要求:\n") print(common)
内容的提问来源于stack exchange,提问作者IRezzet
相关产品推荐
相关产品推荐

