0

ユーザーにこれを許可しようとしています:

最初に、テキストに次のように書かれているとしましょう:

"hello world hello earth"

ユーザーが「hello」を検索すると、次のように表示されます。

|hello| world |hello| earth

ここに私が持っているものがあります:

m = re.compile(pattern)
i =0
match = False
while i < len(self.fcontent):
    content = " ".join(self.fcontent[i])
    i = i + 1;
    for find in m.finditer(content):    
        print i,"\t"+content[:find.start()]+"|"+content[find.start():find.end()]+"|"+content[find.end():]
        match = True
        pr = raw_input( "(n)ext, (p)revious, (q)uit or (r)estart? ")
        if (pr == 'q'):
            break
        elif (pr == 'p'):
            i = i -  2
        elif (pr == 'r'):
            i = 0
if match is False:
    print "No matches in the file!"

どこ :

pattern = user specified pattern
fcontent = contents of a file read in and stored as array of words and lines e.g:
[['line','1'],['line','2','here'],['line','3']]

ただし、印刷されます

|hello| world hello earth
hello world |hello| earth

2 つの行を結合して 1 つに表示するにはどうすればよいですか? ありがとう

編集

これは、より大きな検索関数の一部であり、パターン..この場合、単語「hello」がユーザーから渡されるため、正規表現の検索/一致/検索を使用してパターンを見つける必要があります。ユーザーは "[0-9]$" を検索することを選択でき、それは終了番号を | の間に挿入することを意味するため、置換およびその他の方法は残念ながら機能しません。

4

4 に答える 4

2

それだけをしている場合は、を使用してくださいstr.replace

print self.content.replace(m.find, "|%s|" % m.find)
于 2012-07-29T16:55:10.273 に答える
2

次のように正規表現を使用できます。

import re
src = "hello world hello earth"
dst = re.sub('hello', '|hello|', src)
print dst

または文字列置換を使用します。

dst = src.replace('hello', '|hello|')
于 2012-07-29T17:04:01.713 に答える
1

OPは単語がそれ自体で立つことを確認したので、元の解決策に戻ります(つまり、別の単語の部分文字列ではありません)。

target = 'hello'
line = 'hello world hello earth'
rep_target = '|{}|'.format(target)

line = line.replace(target, rep_target)

収量:

|hello| world |hello| earth
于 2012-07-29T17:05:45.170 に答える
0

あなたの例に基づいて指摘されているように、 str.replace を使用するのが最も簡単です。より複雑な基準が必要な場合は、次のように調整できます...

import re

def highlight(string, words, boundary='|'):
    if isinstance(words, basestring):
        words = [words]
    rs = '({})'.format(boundary.join(sorted(map(re.escape, words), key=len, reverse=True)))
    return re.sub(rs, lambda L: '{0}{1}{0}'.format(boundary, L.group(1)), string)
于 2012-07-29T17:29:40.810 に答える