25

私は自分のテキストを実行し、データベースに基づいて書いたすべての文を検索して置き換えるスクリプトを持っています。

スクリプト:

with open('C:/Users/User/Desktop/Portuguesetranslator.txt') as f:
    for l in f:
        s = l.split('*')
        editor.replace(s[0],s[1])

データベースの例:

Event*Evento*
result*resultado*

等々...

今起こっていることは、問題を抱えていることに気付いたので、そのスクリプトで「単語全体のみ」が必要だということです。

たとえば、 Resultandを使用すると、 EventforResultadoとを置き換えてEvento、テキスト内でもう一度スクリプトを実行すると、スクリプトは再びResultadoand を置き換えるためEventoです。

そして、スクリプトを実行した後の結果は、このままResultadoadoですEventoo.

ご存知のように..イベントと結果だけでなく、検索と置換が機能するように設定した1000以上の文があります..

単純な検索と 2 つの単語の置換は必要ありません..さまざまな文に対してデータベースを何度も編集するので..

4

5 に答える 5

12

re.sub通常の文字列置換の代わりに使用して、単語全体のみを置換します。したがって、スクリプトを再度実行しても、既に置換された単語は置換されません。

>>> import re
>>> editor = "This is result of the match"
>>> new_editor = re.sub(r"\bresult\b","resultado",editor)
>>> new_editor
'This is resultado of the match'
>>> newest_editor = re.sub(r"\bresult\b","resultado",new_editor)
>>> newest_editor
'This is resultado of the match'
于 2013-07-18T18:05:24.570 に答える