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
をしかし、それは、
助けてくれてありがとうまたは任意のヒントを動作しません。以下のコードを参照してください
希望する出力は何ですか? –
出力は次のようにする必要があります:['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'] –
重複がある場合はどうなりますか? 'w0 a a w1'のように' w0 first_word first_word w1'ですか? –