例:天氣為敏感詞。替換成*號(hào)
- str1='今天的天氣沒有昨天的天氣好'
 - str2=str1.replace('天氣','*')
 - print(str2)
 
												for循環(huán)替換多個(gè)敏感字符串
- str1=['今天的天氣沒有昨天的天氣好','明天的天氣預(yù)報(bào)陰天有小雨']
 - for s in str1:
 - s=s.replace('天氣','*')
 - print(s)
 
												Python replace() 方法把字符串中的 old(舊字符串)替換成 new(新),如果指定第三個(gè) max,則替換不超過參數(shù) max 次。
實(shí)例:
- str.replace(舊,新 [替換次數(shù)])
 
- str1='今天的天氣沒有昨天的天氣好'
 - str2=str1.replace('天氣','weather')
 - #限制替換1次
 - str3=str1.replace('天氣','weather',1)
 - print(str2)
 - print(str3)
 
												需求讀取敏感詞庫,替換文件內(nèi)包含敏感詞匯的字符串為*
敏感詞匯:
- mg=['天氣','*預(yù)']
 - str1=['今天的天氣沒有昨天的天氣好','明天的天氣預(yù)報(bào)陰天有小雨','今天的weather真好']
 - def r_str(s,a):
 - #s:要檢測(cè)的字符串,
 - #a:敏感字符串列表
 - new_str =s
 - for a1 in a:
 - if a1 in s:
 - new_str=s.replace(a1,'*'*len(a1))
 - # print(new_str)
 - if new_str==s:
 - # exit(new_str)
 - return new_str
 - else:
 - return r_str(new_str,a)
 - #調(diào)用替換函數(shù)
 - for s in str1:
 - print(r_str(s,mg))