You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何不修改原输入实现忽略空格的字符串匹配

Python 实现忽略连续要求的分散字符串匹配

你当前用的a in b是严格连续子串匹配,自然无法匹配分散存在的词,直接根据实际匹配需求选对应实现即可:

基础实现:只要a中所有空格分隔的内容都在b中出现即可(不要求是完整单词、不要求顺序)

直接拆分a的分词后逐个判断存在性即可:

a = 'hello world'
b = 'Hi world and hello user'

def loose_match(pattern: str, text: str) -> bool:
    # split()不传参时会自动按任意空白(多空格、换行、制表符)拆分,自动忽略首尾空白
    pattern_parts = pattern.split()
    return all(part in text for part in pattern_parts)

loose_match(a, b)  # 返回True

优化实现:匹配完整独立单词(避免子串误判)

上面的基础实现会出现短词误匹配长词子串的问题,比如pattern里的he会匹配到text里的hello。如果要匹配完整的独立单词,先把text的分词转成集合再判断,查询效率更高也更准确:

def whole_word_match(pattern: str, text: str) -> bool:
    pattern_parts = pattern.split()
    text_words = set(text.split())
    return all(part in text_words for part in pattern_parts)

顺序匹配实现:要求a中单词按原有顺序出现在b中,允许中间插入其他内容

如果需要保持a里单词的出现顺序,只是不要求连续,可以用迭代器的懒加载特性实现:

def order_match(pattern: str, text: str) -> bool:
    pattern_parts = pattern.split()
    text_word_iter = iter(text.split())
    return all(part in text_word_iter for part in pattern_parts)

举个例子:a是hello world,b是Hi hello and world user会返回True,b是world hello会返回False,符合顺序匹配要求。


内容的提问来源于stack exchange,提问作者Bobby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 02:57:20