我有現成的如下兩個列表:查找表的字和替換它在Python 2.7
list_a = ['one','two','three','four','five','six','seven',...]
list_content = ['This is 1st sentence with one.',
'This is 2nd sentence with seven.',
'This is 3rd sentence with one and two.',
'This is 4th sentence with three, five, and six.',...]
的想法是每個句子從list_a找到一個詞list_content並將它們替換爲'__'以進行完全匹配。
輸出應該是這樣的:
list_output = ['This is 1st sentence with ___.',
'This is 2nd sentence with ___.',
'This is 3rd sentence with ___ and ___.',
'This is 4th sentence with ___, ___, and ___.',...]
使用應用re.sub我嘗試:
for each_sent in list_content:
for word in list_a:
result = re.sub(r'\b' + word + r'\b', '__', each)
print result
它似乎並沒有被替換爲輸出。
變化'結果=應用re.sub(R '\ B' +字+ R '\ B', '__',每個)''到each_sent =重.sub(r'\ b'+ word + r'\ b','__',each_sent)'和'print result' to'print each_sent' –
'result = re.sub(r'\ b'+ word + r'\ b','__',each)'change' each' to'each_sent' –
你是一位功夫熊貓!你救了我的命! :) – htetmyet