【发布时间】:2017-07-11 11:52:26
【问题描述】:
我正在尝试将句子中的特定单词替换为不同的名称,每个单词都会有一个新名称。例如:
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)将在第二句中替换为'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吗? -
如果有重复的话,第一个单词会被替换,第二个单词会被忽略
-
@S.M 如果你的第一个项目是
['b', 'a'],那么第一个对应的元素是w0 w1 second_word w2 w3 first_word w4吗?
标签: python