在字符网格中匹配加号

2024-09-19 21:30:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用正则表达式匹配字符串中的模式。想法是这样的。在

我有一个大小为n*m的数组,每个条目中都有G和非G。我必须找到G的模式,以加号(+)的形式,所有的加号的四个臂都有相同的大小。例如,在下面给出的示例中:

BGBBGB
GGGGGG
BGBBGB
GGGGGG
BGBBGB
BGBBGB

BGB
GGG
BGB

是加号(+)的一种形式,每个臂的大小为1。在

我试图用正则表达式来解决这个模式,但是,它对我来说并不奏效。在

^{pr2}$

只匹配水平轴上手臂长度相同的图案,中间有一个G。不知道如何匹配四个边上手臂长度相同的G的图案。感谢您的回答。在


Tags: 字符串示例模式条目数组形式图案手臂
2条回答

我会选择使用类似矩阵的方法来解决这个问题,而不是使用正则表达式。 在您的示例中,我假设l是一个类似于包含每一行数据的列表。在

import pandas as pd
import numpy as np


def findPlusSigh(data, pattern):
    # Find indexes which match the pattern
    data = data == pattern
    pattern_index = data.nonzero()
    # List to store result
    result = []
    center_index = []
    # Loop over each matched element
    for i, j in zip(pattern_index[0], pattern_index[1]):
        # Look for arm length from 1 to 100
        for m in range(1, 100):
            try:
                # Break the loop if it's out of range of the data
                if m > i or m > j:
                    break
                # check the matched pattern in 4 directions, i.e., up, left,
                # down, right
                if (all(data[([i-m, i, i+m, i], [j, j-m, j, j+m])])):
                    pass
                else:
                    break
            except:
                break
        # If arm length >= 1
        if m > 1:
            # When the loop breaks, m is 1 more than the actual arm length
            # So we need to minus 1
            # Record the arm length
            result.append(m-1)
            # Record the center index
            center_index.append((i, j))
    return(result, center_index)

# Test data
l = ['BGBBGB', 'GGGGGG', 'BGBBGB', 'GGGGGG', 'BGBBGB', 'BGBBGB']
# The pattern you are matching
pattern = 'G'
# Convert the n by m data into an array where each element is a character
data = np.array([np.array(list(x)) for x in l])
result, center_index = findPlusSigh(data, pattern)
for i, j in zip(result, center_index):
    print ("Data center (Row {}, Column{}) has a plus sign length of {}".format(
        j[0]+1, j[1]+1, i))

据我所知,正则表达式在一维数组中使用时是有用的,而不是像问题中那样用于二维数组。在

所以我倾向于说,使用正则表达式可能不是一个好方法。。。我试图将一个固定的图案与G+图案中的位置相匹配,每个手臂都有1个单位长:

B = 0
G = 1

matrix = (
    (B, G, B, B, G, B),
    (G, G, G, G, G, G),
    (B, G, B, B, G, B),
    (B, G, B, B, G, B),
    (G, G, G, G, G, G),
    (B, G, B, B, G, B),
)

pattern = (
    (B, G, B),
    (G, G, G),
    (B, G, B),
)

def getMatrixSize(mat):
    # Return (width, height)
    return (len(mat[0]), len(mat))

def findPattern(mat, pat):
    matches = []

    matsize = getMatrixSize(mat)
    patsize = getMatrixSize(pat)

    for y in range(matsize[1] - patsize[1] + 1):
        for x in range(matsize[0] - patsize[0] + 1):

            submat_cols = mat[y:y+patsize[1]]
            for i in range(patsize[1]):
                submat_row = submat_cols[i][x:x+patsize[0]]
                if submat_row != pat[i]:
                    i = -1
                    break

            if i > 0:
                matches.append((x, y))

    return matches

# Run the thing
print(findPattern(matrix, pattern))

我的想法是在矩阵上滑动模式,然后在矩阵的每个子段上比较模式的每个片段。。。在

现在这是某种模式的“硬编码”。
但你可以从这一点出发,尝试让模式发展(不同的手臂长度)

注意:问题在于,使用正则表达式,您不能执行\w{A}.\w{A}这样的操作,A将是一个共享计数器。。。至少我从没听说过。在

相关问题 更多 >