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

Python实现:检测列表多词是否在字符串内且位置邻近

问题:检测字符串中邻近的目标单词组

原始数据

string = """Ventilation box with reference VE03 with soundproofed box with inspection door
with the following technical characteristics: Air flow: 250 l s Available static pressure:
200 Pa With voltage regulator With characteristics according to project technical data
sheets Model make: CVB 4 180 180N or equivalent Includes flexible anti-vibration tarpaulins
at the air connections and metal dampers and supports Includes cable."""

list1 = ["CVB","1100","250"]
list2 = ["CVB","4","180","180N","RE","147W"]

需求

检查字符串中是否存在列表内2个及以上的单词,且这些单词彼此处于前后5个单词的邻近范围内:

  • 使用list1应返回False(CVB和250位置相距过远)
  • 使用list2应返回True(CVB、4、180、180N连续相邻)

原代码仅实现了计数存在的单词,无法判断位置邻近性,以下是优化后的实现:

优化后的代码

import re

def check_nearby_words(target_string, word_list, proximity=5):
    # 清理字符串中的标点符号,替换为空格
    cleaned_string = re.sub(r'[^\w\s]', ' ', target_string)
    # 分割为单词列表,过滤空字符串
    clean_words = [word for word in cleaned_string.split() if word]
    
    # 收集所有目标单词在单词列表中的位置索引
    positions = []
    for target_word in word_list:
        for idx, word in enumerate(clean_words):
            if word == target_word:
                positions.append(idx)
    
    # 不足2个目标单词出现,直接返回False
    if len(positions) < 2:
        return False
    
    # 检查是否存在任意两个位置的距离在邻近范围内
    for i in range(len(positions)):
        for j in range(i + 1, len(positions)):
            if abs(positions[i] - positions[j]) <= proximity:
                return True
    return False

# 测试用例
string = """Ventilation box with reference VE03 with soundproofed box with inspection door
with the following technical characteristics: Air flow: 250 l s Available static pressure:
200 Pa With voltage regulator With characteristics according to project technical data
sheets Model make: CVB 4 180 180N or equivalent Includes flexible anti-vibration tarpaulins
at the air connections and metal dampers and supports Includes cable."""

list1 = ["CVB","1100","250"]
list2 = ["CVB","4","180","180N","RE","147W"]

print(check_nearby_words(string, list1))  # 输出: False
print(check_nearby_words(string, list2))  # 输出: True

实现思路

  1. 字符串预处理:用正则替换掉所有非单词、非空格的字符,再分割成干净的单词列表,避免标点干扰单词匹配
  2. 位置收集:遍历目标单词列表,记录每个目标单词在干净单词列表中的所有出现位置
  3. 邻近性检查:遍历所有位置对,只要存在任意两个位置的索引差不超过设定的邻近范围(默认5),就返回True;若没有符合条件的配对或目标单词出现不足2个,返回False

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 11:00:47