匹配不完整限定路径

72 阅读2分钟

在某些情况下,我们可能需要匹配不完整限定路径,这些路径缺少一些部分,但保证具有两个属性:

  1. 不完整路径和完全限定路径的最后一部分完全相等。
  2. 不完整路径的每个部分的顺序与完全限定路径的每个部分的顺序相匹配。

huake_00066_.jpg 例如,考虑以下路径:

p1 = '/foo/baz/myfile.txt' p2 = '/bar/foo/myfile.txt' actual = '/foo/bar/baz/myfile.txt' www.jshk.com.cn/mb/reg.asp?…

在这种情况下,p1 将匹配,但 p2 将不会匹配,因为在实际路径中,bar 出现在 foo 之后。我们可以使用以下代码来匹配这些路径:

def match(strs, actual):
    seen = {}
    act = actual.split('/')
    for x in strs.split('/'):
        if x in seen:
            # 如果该项已经见过,则在先前匹配的索引之后开始搜索
            ind = act.index(x, seen[x]+1)
            yield ind
            seen[x] = ind
        else:
            ind = act.index(x)
            yield ind
            seen[x] = ind

2、解决方案 方法 1:使用 list.index:

>>> p1 = '/foo/baz/myfile.txt'
>>> p2 = '/bar/foo/myfile.txt'
>>> actual = '/foo/bar/baz/myfile.txt'
>>> list(match(p1, actual))     # 有序列表,因此匹配
[0, 1, 3, 4]
>>> list(match(p2, actual))     # 无序列表,不匹配
[0, 2, 1, 4]

>>> p1 = '/foo/bar/bar/myfile.txt'
>>> p2 = '/bar/bar/baz/myfile.txt'
>>> actual = '/foo/bar/baz/bar/myfile.txt'
>>> list(match(p1, actual))     # 有序列表,因此匹配
[0, 1, 2, 4, 5]
>>> list(match(p2, actual))     # 无序列表,不匹配
[0, 2, 4, 3, 5]

方法 2:使用 defaultdict 和 deque:

from collections import defaultdict, deque
def match(strs, actual):
    indexes_act = defaultdict(deque)
    for i, k in enumerate(actual.split('/')):
        indexes_act[k].append(i)
    prev = float('-inf')
    for item in strs.split('/'):
        ind = indexes_act[item][0]
        indexes_act[item].popleft()
        if ind > prev:
            yield ind
        else:
            raise ValueError("Invalid string")
        prev = ind

Demo:
>>> p1 = '/foo/baz/myfile.txt'
>>> p2 = '/bar/foo/myfile.txt'
>>> actual = '/foo/bar/baz/myfile.txt'
>>> list(match(p1, actual))
[0, 1, 3, 4]
>>> list(match(p2, actual))
    ...
    raise ValueError("Invalid string")
ValueError: Invalid string

>>> p1 = '/foo/bar/bar/myfile.txt'
>>> p2 = '/bar/bar/baz/myfile.txt'
>>> actual = '/foo/bar/baz/bar/myfile.txt'
>>> list(match(p1, actual))
[0, 1, 2, 4, 5]
>>> list(match(p2, actual))
    ...
    raise ValueError("Invalid string")
ValueError: Invalid string

方法 3:使用迭代器:

def match(path, actual):
    path = path.strip('/').split('/')
    actual = iter(actual.strip('/').split('/'))
    for pathitem in path:
        for item in actual:
            if pathitem == item:
                break
        else:
            # The for-loop never breaked, so pathitem was never found
            return False
    return True

q1 = '/foo/baz/myfile.txt'
q2 = '/bar/foo/myfile.txt'
p1 = '/foo/bar/bar/myfile.txt'
p2 = '/bar/bar/baz/myfile.txt'
actual = '/foo/bar/baz/bar/myfile.txt'

print(match(q1, actual))
# True

print(match(q2, actual))
# False

print(match(p1, actual))
# True

print(match(p2, actual))
# False