字符串搜索在python中返回匹配的行

时间:2011-07-20 11:23:01

标签: python string-matching

我在python中很新。我想在文件的某些行中匹配字符串。让我们说, 我有字符串:

british    7
German     8
France     90

我在文件中有一些行:

<s id="69-7">...Meanwhile is the studio 7 album by British pop band 10cc.</s>
<s id="15-8">...And Then There Were Three... is the ninth studio album by the german band Genesis 8 and was released in 1978.</s>
<s id="1990-2">Magnum Nitro Express is a France centerfire fire rifle cartridge 90.</s>

我希望输出如下:

<s id="69-7">...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc.</s>
<s id="15-8">...And Then There Were Three... is the ninth studio album by the <w1>german</w1> band Genesis <w2>8</w2> and was released in 1978.</s>
<s id="1990-2">Magnum Nitro Express is a <w1>France</w1> centerfire fire rifle cartridge <w2>90</w2>.</s>

我尝试使用以下代码:

for i in file:      
    if left in i and right in i:
        line = i.replace(left, '<w1>' + left + '</w1>')
        lineR = line.replace(right, '<w2>' + right + '</w2>')
        text = text + lineR + "\n"
        continue
     return text

但是,它也匹配来自id.eg的字符串。

<s id="69-<w2>7</w2>">...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc.</s>

那么,有没有办法搜索字符串作为字符而不是字符,以便我可以逃避<s id="69-<w2>7</w2>">

提前感谢您提供任何帮助。

3 个答案:

答案 0 :(得分:4)

我有一些比较复杂的东西,但是我匆匆写了这篇文章,现在它完成了这项工作。

请注意:

  • 我在之后添加了'in France'同时是英国流行乐队10cc的工作室7专辑
    只有英国被修改

  • '1978'在由德国乐队Genesis 8发布并于1978年发布未修改,而'8'被修改。

这就是复杂的原因。

但是我担心,尽管存在这种复杂情况,但对于所有可能的句子来说并不准确。

应该做出改进,使 idi 始终是正确的音乐组名称,并不总是第一个,就像现在的解决方案一样。但是如果不知道你到底想要什么,这是一项艰苦的工作

ss ='''british    7
German     8
France     90'''


text = '''<s id="69-7">...Meanwhile is the studio 7 album by British pop band 10cc in France.</s>
<s id="15-8">...And Then There Were Three... is the ninth studio album by the german band Genesis 8 and was released in 1978.</s>
<s id="1990-2">Magnum Nitro Express is a France centerfire fire rifle cartridge 90.</s>
'''




import re
regx = re.compile('^(.+?)[ \t]+(\d+)',re.MULTILINE)




dico = dict((a.lower(),b) for (a,b) in regx.findall(ss))
print 'dico==',dico
print '\n\n'



rogx = re.compile('(<s id="[\d-]+">|</s>\r?\n)')
splitted = rogx.split(text)
print 'splitted==\n',splitted

print '=================\n'

def repl(mat):
    idi = (b for (a,b) in the if b).next().lower()
    x,y = mat.groups()
    if x:
        if dico[idi.lower()]==x:
            return '<w2>%s</w2>' % x
        else:
            return x
    if y :
        if y.lower()==idi:
            return '<w1>%s</w1>' % y
        else:
            return y

rigx = re.compile('(\d+)|(' + '|'.join(dico.keys()) + ')',re.IGNORECASE)

for i,el in enumerate(splitted[0::2]):
    if el:
        print '-----------------------------'
        print '* index in splitted==',2*i
        print '\n* el==\n',repr(el)
        print '\n* rigx.findall(el)==\n',rigx.findall(el)
        the = rigx.findall(el)
        print '\n* modified el:\n',rigx.sub(repl,el)
        splitted[2*i] = rigx.sub(repl,el)


print '\n\n##################################\n\n'

print 'modified splitted==\n',splitted
print
print ''.join(splitted)

结果

dico== {'german': '8', 'british': '7', 'france': '90'}



splitted==
['', '<s id="69-7">', '...Meanwhile is the studio 7 album by British pop band 10cc in France.', '</s>\n', '', '<s id="15-8">', '...And Then There Were Three... is the ninth studio album by the german band Genesis 8 and was released in 1978.', '</s>\n', '', '<s id="1990-2">', 'Magnum Nitro Express is a France centerfire fire rifle cartridge 90.', '</s>\n', '']
=================

-----------------------------
* index in splitted== 2

* el==
'...Meanwhile is the studio 7 album by British pop band 10cc in France.'

* rigx.findall(el)==
[('7', ''), ('', 'British'), ('10', ''), ('', 'France')]

* modified el:
...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc in France.
-----------------------------
* index in splitted== 6

* el==
'...And Then There Were Three... is the ninth studio album by the german band Genesis 8 and was released in 1978.'

* rigx.findall(el)==
[('', 'german'), ('8', ''), ('1978', '')]

* modified el:
...And Then There Were Three... is the ninth studio album by the <w1>german</w1> band Genesis <w2>8</w2> and was released in 1978.
-----------------------------
* index in splitted== 10

* el==
'Magnum Nitro Express is a France centerfire fire rifle cartridge 90.'

* rigx.findall(el)==
[('', 'France'), ('90', '')]

* modified el:
Magnum Nitro Express is a <w1>France</w1> centerfire fire rifle cartridge <w2>90</w2>.


##################################


modified splitted==
['', '<s id="69-7">', '...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc in France.', '</s>\n', '', '<s id="15-8">', '...And Then There Were Three... is the ninth studio album by the <w1>german</w1> band Genesis <w2>8</w2> and was released in 1978.', '</s>\n', '', '<s id="1990-2">', 'Magnum Nitro Express is a <w1>France</w1> centerfire fire rifle cartridge <w2>90</w2>.', '</s>\n', '']

<s id="69-7">...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc in France.</s>
<s id="15-8">...And Then There Were Three... is the ninth studio album by the <w1>german</w1> band Genesis <w2>8</w2> and was released in 1978.</s>
<s id="1990-2">Magnum Nitro Express is a <w1>France</w1> centerfire fire rifle cartridge <w2>90</w2>.</s>

编辑1

我删除了replmodel()

repl()获取rigx.findall(el)的值 我为

添加了一行 = rigx.findall(el)

答案 1 :(得分:3)

您应该使用正则表达式专门替换单个单词,而不是单词部分。

这样的东西
import re
left='british'
right='7'
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)
print(i2)

给了我们'<s id="69-7">...Meanwhile is the studio <w2>7</w2> album by <w1>British</w1> pop band 10cc.</s>'

如果这种方法导致错误,您可以尝试更精确的代码,例如

import re

def do(left, right, line):
    parts = [x for x in re.split('(<[^>]+>)', line) if x]
    for idx, l in enumerate(parts):
        lu = l.upper()
        if (not ('<s' in l or 's>' in l) and
            (left.upper() in lu and right.upper() in lu)):
            l = re.sub('(?i)(\s+)(%s)(\s+)'%left, '\\1<w1>\\2</w1>\\3', l)
            l = re.sub('(?i)(\s+)(%s)(\s+)'%right, '\\1<w2>\\2</w2>\\3', l)
            parts[idx] = l

    return ''.join(parts)


line = '<s id="69-7">...Meanwhile is the studio 7 album by British pop band 10cc.</s>'
print(do('british', '7', line))
print(do('british', '-7', line))

答案 2 :(得分:1)

最好的方法是使用正则表达式。 但是如果'left'和'right'总是至少有一个尾随和前导空间,那么你可以使用一个简单的技巧(只需在你的模式中添加前导和尾随空格):

line = file.replace(' ' + left + ' ', ' <w1>' + left + '</w1> ')
lineR = line.replace(' ' + right + ' ', ' <w2>' + right + '</w2> ')