2017-07-11 14 views
2

文中の特定の単語を別の名前に置き換えようとしていますが、各単語には新しい名前が付けられます。例えば:文中の特定の単語をPythonの別の名前に置き換えてください。

my_words = {[ 'a','b'],['c','d','e','f'], ['l','m','n']} 
my_sentences = {' w0 w1 a w2 w3 b w4' , ' w0 w1 w2 c w3 d w4 e f' , 'w0 w1 w2 l m w3 w4 n w5'] 

私は(a,'first_word')を交換すると、最初の文で(b ,' second_word')を交換したいです。また、(c,'first_word')(d, 'second_word')を置き換えたいとします。リスト(e、f)の残りの単語は、2番目の文の'other_word'に置き換えられます。 すべての特定の単語を'first_word'に置き換えるコードを書きました。私は別のコードを試みた

def replace_all(sentences=[], words = []): 
    text = [] 
    A_regex = re.compile('|'.join(map(re.escape, words))) 
    for t in sentences: 
     t = A_regex.sub("first_word", t) 
     text.append(t) 
    return text 

for t in sentences: 
    for w in words: 
     for j in range (len(w)): 
      t = t.replace(w[j][0],'FIRST_word') 
      t = t.replace(w[j][1],'SECOND_word') 
      if j == -1: 
       break 
      else: 
       t = t.replace(w[j][2:-1],'OTHER_words') 
    break 

をしかし、それは、

助けてくれてありがとうまたは任意のヒントを動作しません。以下のコードを参照してください

+1

希望する出力は何ですか? –

+0

出力は次のようにする必要があります:['w0 w1 first_word w2 w3 second_word w4'、 'w0 w1 w2 first_word w3 second_word w4 other_word other_word'、 'w0 w1 w2 first_word second_word w3 w4 other_word w5'] –

+0

重複がある場合はどうなりますか? 'w0 a a w1'のように' w0 first_word first_word w1'ですか? –

答えて

0

あなたのアプローチに続いて、次のようにそれを修正することができます:

# You need to add spaces before and after each letter to avoid replacing letters in words. 
my_words = [[' a ', ' b '], [' c ', ' d ', ' e ', ' f '], [' l ', ' m ', ' n ']] 
my_sentences = ['w0 w1 a w2 w3 b w4', ' w0 w1 w2 c w3 d w4 e f', 'w0 w1 w2 l m w3 w4 n w5'] 
for i, c in enumerate(my_words): 
    for j, word in enumerate(c): 
     if j == 0: 
      my_sentences[i] = my_sentences[i].replace(word, ' first_word ') 
     elif j == 1: 
      my_sentences[i] = my_sentences[i].replace(word, ' second_word ') 
     else: 
      my_sentences[i] = my_sentences[i].replace(word, ' other_word ') 
print my_sentences 

出力:

['w0 w1 first_word w2 w3 second_word w4', ' w0 w1 w2 first_word w3 second_word w4 other_word f', 'w0 w1 w2 first_word second_word w3 w4 other_word w5'] 

しかし、私は非常にあなたの代わりに、より効率のためdictionaryを使用することをお勧めします。

関連する問題