匹配Python中最长的子字符串

2024-09-20 03:38:02 发布

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

假设我在文本文件的左右部分之间有一个制表符的以下字符串:

The dreams of REM (Geo) sleep         The sleep paralysis

我要匹配上面的字符串,该字符串在另一个以下文件的每一行中同时匹配左部分和右部分:

^{pr2}$

如果无法与填充字符串匹配,则尝试与子字符串匹配。在

我想用最左边和最右边的模式搜索。 例如(最左边的情况)

The dreams of REM  sleep     paralysis
The dreams of REM  sleep     The sleep

例如(大多数情况下):

REM  sleep    The sleep paralysis
The dreams of   The sleep paralysis

再次感谢你的帮助。在


Tags: 文件ofthe字符串模式情况sleep制表符
1条回答
网友
1楼 · 发布于 2024-09-20 03:38:02

(好吧,你澄清了大部分你想要的。让我重申一下,然后澄清我在下面列出的仍然不清楚的要点。。。另外,把我给你看的入门代码改编一下,把结果发给我们。)

您希望逐行、不区分大小写地搜索一对匹配模式中每一个的最长连续匹配。所有的模式似乎都是不相交的(patternX和patternY不可能匹配,因为它们使用不同的短语,例如不能同时匹配“额叶”和“前额叶皮层”)。在

您的模式是以一系列对的形式提供的,('dom','rang'),=>;让我们通过它们的下标[0]和[1来引用它们,您可以使用字符串.拆分('\t')来获取它。) 重要的是匹配线必须匹配domrang模式(全部或部分)。 顺序是独立的,因此我们可以匹配rang然后dom,反之亦然=>;每行使用2个单独的正则表达式,并测试d和r是否匹配。在

模式有可选部分,在括号中=>;所以只需使用(optionaltext)?语法将其写入/转换为regex语法,例如:re.compile('Frontallobes of (leftside)? the brain', re.IGNORECASE)

返回值应该是迄今为止子字符串匹配最长的字符串缓冲区。在

现在有几件事需要澄清-请编辑您的问题,解释如下:

  • 如果找到任何一对模式的完全匹配,则返回该值。在
  • 如果找不到任何完全匹配项,则搜索两个模式对的部分匹配项。其中“部分匹配”是指模式中“最多的单词”或“单词的最高比例(%)”?假设我们排除了对单词“the”的伪匹配,在这种情况下,我们只需从搜索模式中省略“the”,就不会损失任何内容,那么这就保证了与任何模式的所有部分匹配都是有意义的。在
  • 我们评分部分匹配(不知何故),例如“包含模式X中的大多数单词”或“包含模式X中最高百分比的单词”。我们应该对所有模式都这样做,然后返回得分最高的模式。你需要考虑一下,匹配两个5字模式的单词(40%)是否更好,比如“梦见”,还是2个单词中的1个(50%),例如“前额而不是皮层”?我们如何打破关系等?如果我们只匹配“睡眠”而不匹配其他内容,会发生什么?在

以上每一个问题都会影响解决方案,所以您需要为我们解答。当你只需要一些简单的东西时,写几页代码来解决最一般的情况是没有意义的。 一般来说,这被称为“NLP”(自然语言处理)。你可能最终会使用NLP库。在

到目前为止,准则的总体结构听起来像:

import re

# normally, read your input directly from file, but this allows us to test:
input = """The pons also contains the sleep paralysis center of the brain as well as generating the dreams of REM sleep.
The optic tract is a part of the visual system in the brain.
The inferior frontal gyrus is a gyrus of the frontal lobe of the human brain.
The prefrontal cortex (PFC) is the anterior part of the frontallobes of the brain, lying in front of the motor and premotor areas.
There are three possible ways to define the prefrontal cortex as the granular frontal cortex as that part of the frontal cortex whose electrical stimulation does not evoke movements.
This allowed the establishment of homologies despite the lack of a granular frontal cortex in nonprimates.
Modern  tracing studies have shown that projections of the mediodorsal nucleus of the thalamus are not restricted to the granular frontal cortex in primates.
""".split('\n')

patterns = [
    ('(dreams of REM (Geo)? sleep)', '(sleep paralysis)'),
    ('(frontal lobe)',            '(inferior frontal gyrus)'),
    ('(prefrontal cortex)',       '(frontallobes of (leftside )?(the )?brain)'),
    ('(modern tract)',            '(probably mediodorsal nucleus)') ]

# Compile the patterns as regexes
patterns = [ (re.compile(dstr),re.compile(rstr)) for (dstr,rstr) in patterns ]

def longest(t):
    """Get the longest from a tuple of strings."""
    l = list(t) # tuples can't be sorted (immutable), so convert to list...
    l.sort(key=len,reverse=True)
    return l[0]

def custommatch(line):
    for (d,r) in patterns:
        # If got full match to both (d,r), return it immediately...
        (dm,rm) = (d.findall(line), r.findall(line))
        # Slight design problem: we get tuples like: [('frontallobes of the brain', '', 'the ')]
        #... so return the longest match strings for each of dm,rm
        if dm and rm: # must match both dom & rang
            return [longest(dm), longest(rm)]
        # else score any partial matches to (d,r) - how exactly?
        # TBD...
    else:
        # We got here because we only have partial matches (or none)
        # TBD: return the 'highest-scoring' partial match
        return ('TBD... partial match')

for line in input:
    print custommatch(line)

在您当前提供的7行输入上运行可以得到:

^{pr2}$

相关问题 更多 >