0

Python正規表現を使用して、先頭と末尾の任意の引用文字列を個別に任意の文字列に置き換えるにはどうすればよいですか?

サンプル入力文字列

This is a "quote" and here's another "quote"

また

This is a “quote&rdquo" and here's another “quote”

サンプル出力文字列

This is a “quote” and here's another “quote”

また

This is a <span>"quote"</span> and here's another <span>"quote"</span>
4

4 に答える 4

2

これは、任意の引用符のペアを処理し、それらを「テキスト」、つまり出力 2 に変換する回答の変形ですre.sub

quotes = [('"', '"'), ("&ldquot;", "&rdquot;")]
left = '|'.join(re.escape(t[0]) for t in quotes)
right = '|'.join(re.escape(t[1]) for t in quotes)
regex = r'((%s)(.*?)(%s))' % (left, right)
outstr = re.sub(regex, r'<span>"\3"</span>', instr)

入力文字列をテストするには:

>>> replace = lambda x: re.sub(regex, r'<span>"\3"</span>', x)
>>> replace('''This is a "quote" and here's another "quote"''')
'This is a <span>"quote"</span> and here\'s another <span>"quote"</span>'
>>> replace('''This is a &ldquot;quote&rdquot; and here's another &ldquot;quote&rdquot;''')
'This is a <span>"quote"</span> and here\'s another <span>"quote"</span>'
于 2012-11-02T16:45:06.547 に答える
0

私は次の非正規表現ソリューションを作成しましたが、より良い方法があるかもしれませんか?

def replace_quotes(value, leadqt='"', tailqt='"', leadrep='<span>', tailrep='</span>', inc=True):
    while leadqt in value:
        value = value.replace(leadqt, leadrep, 1).replace(tailqt,tailrep,1)
    if inc:
        value = value.replace(leadrep, '%s%s' % (leadrep, leadqt)).replace(tailrep, '%s%s' % (tailqt, tailrep))
    return value

試して...

>>> MYSTR = "This is a \"quote\" and here's another \"quote\""
>>> replace_quotes(MYSTR)
u'This is a <span>"quote"</span> and here\'s another <span>"quote"</span>'
于 2012-11-02T16:42:01.440 に答える
0

これは、ネストされた引用符では機能しませんが、次のようになります。

s = 'This is a "quote" and here\'s another "quote"'
re.sub(r'"(.*?)"', r'<span>\1</span>', s)
# "This is a <span>quote</span> and here's another <span>quote</span>"

そして、それを次のようにラップします。

def rep_quote(s, begin, end):
    return re.sub(r'"(.*?)"', r'{}\1{}'.format(re.escape(begin), re.escape(end)), s)
于 2012-11-02T16:47:34.140 に答える
0

このようなもの:

>>> st='''This is a "quote" and here's another "quote"'''
>>> words=re.findall(r'"\w+"',st)
>>> for x in set(words):
...     st=st.replace(x,'<span>'+x+'</span>')
... 

>>> print st
This is a <span>"quote"</span> and here's another <span>"quote"</span>
于 2012-11-02T16:47:47.473 に答える