2016-05-13 16 views
-3
import re 
def multiwordReplace(text, wordDic): 
    rc = re.compile('|'.join(map(re.escape, wordDic)))) 
    def translate(match): 
     return wordDic[match.group(0)] 
    return rc.sub(translate, text) 

このコードは、別のソースからコピーされ、私はそれがテキストの通路に言葉を置き換える方法についてはわからないですし、「再」関数は、ここでこの単語置換機能はどのように機能しますか?

+1

[正規表現](https://docs.python.org/2/howto/regex.html)についてお読みください。 –

+2

このような質問はどうすればよいですか?それは[正規表現が何を意味するか](http://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean)のような質問ではありませんが、それに似ています。 –

答えて

1

ワンピース...

import re 
def generateMwR(wordDic): 
    rc = re.compile('|'.join(map(re.escape, wordDic))) 
    def f(text): 
     def translate(match): 
      print(match.group(0)) 
      return wordDic[match.group(0)] 
     return rc.sub(translate, text) 
    return f 

使い方は次のようになります

# Our dictionary 
wordDic = {'hello': 'foo', 'hi': 'bar', 'hey': 'baz'} 

# Escape every key in dictionary with regular expressions' escape character. 
# Escaping is requred so that possible special characters in 
# dictionary words won't mess up the regex 
map(re.escape, wordDic) 

# join all escaped key elements with pipe | to make a string 'hello|hi|hey' 
'|'.join(map(re.escape, wordDic)) 

# Make a regular expressions instance with given string. 
# the pipe in the string will be interpreted as "OR", 
# so our regex will now try to find "hello" or "hi" or "hey" 
rc = re.compile('|'.join(map(re.escape, wordDic))) 

のでRCは今、辞書にある単語と一致し、rc.subは、指定された文字列内のそれらの単語を置き換えます。変換関数は、正規表現が一致を返すときに、キーの対応する値を返します。

1
  1. re.compile()使用されている理由を理解していないました - 式文字列をregexオブジェクトにコンパイルします。文字列は、worDicの連結キーとセパレータ|で構成されます。 wordDic{'hello':'hi', 'goodbye': 'bye'}文字列は次のようになり考える| tranlatedすることができた「こんにちはこんにちは」に「ハローまたは HI」
  2. def translate(match):は - すべての試合
  3. rc.sub(translate, text)を処理するコールバック関数を定義する - 文字列置換をPerformes。正規表現がテキストにマッチすると、一致(実際にはwordDicのキー)がコールバックを介してwordDicで検索され、翻訳が返されます。

例:

wordDic = {'hello':'hi', 'goodbye': 'bye'} 
text = 'hello my friend, I just wanted to say goodbye' 
translated = multiwordReplace(text, wordDic) 
print(translated) 

出力される。

hi my friend, I just wanted to say bye 

EDIT

正規表現が複数回使用される場合しかしre.compile()を使用することの主な利点は、パフォーマンスの向上であります。関数呼び出しごとに正規表現がコンパイルされるので、何の利得もありません。 wordDicが複数回使用されている場合は、wordDicためmultiwordReplace関数を生成し、コンパイルは一度だけ行われます。作品によって

wordDic = {'hello': 'hi', 'goodbye': 'bye'} 
text = 'hello my friend, I just wanted to say goodbye' 
f = generateMwR(wordDic) 
translated = f(text) 
関連する問題