совпадение строк в питоне - PullRequest
1 голос
/ 31 июля 2011

У меня возникают проблемы со следующим вопросом. Допустим, у меня есть несколько строк в словаре из двух списков:

 left                                right
british                             7
cuneate nucleus                     Medulla oblongata
Motoneurons                         anterior

И у меня есть несколько тестовых строк в файле, как показано ниже:

<s id="69-7">British Meanwhile is the studio 7 album by british pop band 10cc 7.</s>
<s id="5239778-2">Medulla oblongata,the name refers collectively to the cuneate nucleus and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, motoneurons located in the spinal.</s>

Я хочу получить вывод следующим образом:

<s id="69-7"><w2>British</w2> Meanwhile is the studio <w2>7</w2> album by <w1>british</w1> pop band 10cc <w2>7</w2>.</s>
<s id="5239778-2"><w2>Medulla oblongata</w2>,the name refers collectively to the <w1>cuneate nucleus</w1> and gracile nucleus, which are present at the junction between the spinal cord and the <w2>medulla oblongata</w2>.</s>

Я пытался с помощью следующего кода:

import re

def textReturn(left, right):
    text = ""
    filetext = open(text.xml, "r").read()
    linelist = re.split(u'[\n|\r\n]+',filetext)

    for i in linelist:
        left = left.strip()
        right = right.strip()

        if left in i and right in i:
            i1 = re.sub('(?i)(\s+)(%s)(\s+)'%left, '\\1<w1>\\2</w1>\\3', i)
            i2 = re.sub('(?i)(\s+)(%s)(\s+)'%right, '\\1<w2>\\2</w2>\\3', i1)
            text = text + i2 + "\n"         
    return text   

Но это дает мне:

'<s id="69-7">British meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc 7.</s>'.
<s id="5239778-2">Medulla oblongata,the name refers collectively to the <w1>cuneate nucleus</w1> and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, <w1>motoneurons</w2> located in the spinal.</s>

т.е. он не может помечать, если есть строка в начале и конце.

Кроме того, я просто хочу получить те строки, которые соответствуюткак левые, так и правые строки, НЕ другие строки.

Любое решение, пожалуйста!Большое спасибо!!!

Ответы [ 2 ]

3 голосов
/ 31 июля 2011

Он не помечается в начале и в конце, потому что вы ожидаете один или несколько пробелов до и после ключевых слов.

Вместо \s+, используйте \b (разрыв слова).

ADDENDUM

Фактический код:

import re

dict = [('british','7'),('cuneate nucleus','Medulla oblongata'),('Motoneurons','anterior')]

filetext = """<s id="69-7">British Meanwhile is the studio 7 album by british pop band 10cc 7.</s>
<s id="5239778-2">Medulla oblongata,the name refers collectively to the cuneate nucleus and gracile nucleus, which are present at the junction between the spinal cord and the medulla oblongata.</s>
<s id="21120-99">Terior horn cells, motoneurons located in the spinal.</s>
"""

linelist = re.split(u'[\n|\r\n]+', filetext)

s_tag = re.compile(r"(<s[^>]+>)(.*?)(</s>)")

for i in range(3):
    left, right = dict[i]

    line_parts = re.search(s_tag, linelist[i])
    start = line_parts.group(1)
    content = line_parts.group(2)
    end = line_parts.group(3)

    left_match = "(?i)\\b(%s)\\b" % left
    right_match = "(?i)\\b(%s)\\b" % right
    if re.search(left_match, content) and re.search(right_match, content):
        line1 = re.sub(left_match, '<w1>\\1</w1>', content)
        line2 = re.sub(right_match, '<w2>\\1</w2>', line1)
        print(line_parts.group(1) + line2 + line_parts.group(3))

Это основа для краткосрочного решения, но долгосрочногоВы должны попробовать подход парсера XML.

2 голосов
/ 31 июля 2011

Если ваш входной файл будет XML-файлом, почему бы не использовать анализатор XML?Смотрите здесь: 19,5.xml.parsers.expat - Быстрый анализ XML с использованием Expat

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...