第0012道練習題_Python文本查找替換

Python練習題第 0012 題

https://github.com/Show-Me-the-Code/show-me-the-code
第0012題:敏感詞文本文件 filtered_words.txt,裏面的內容 和 0011題一樣,當用戶輸入敏感詞語,則用 星號替換,例如當用戶輸入【北京是個好城市】,則變成【**是個好城市】
敏感詞文件內容如下:
北京
程序員
公務員
領導
牛比
牛逼
你娘
你媽
love
sex
jiangge

可以只用str.replace,也可以用re.sub

Talk is cheap, show you my code.

#! /usr/bin/env python
#! -*- coding: utf-8 -*-

__author__ = 'Sophie'

import re

if __name__ == '__main__':
    file = open("/Users/Sophie/PycharmProjects/Practice_0012/key_word.txt","r")
    list_key_word =[]
    try:
        list_key_word = file.readlines()
    finally:
        file.close()
    for i in range(len(list_key_word)):
        list_key_word[i]=list_key_word[i].strip(" \n")
    while(True):
        userinput = raw_input("Please input something.\n")
        result = ""
        for x in list_key_word:
            #result = userinput.replace(x,"*")
            result = re.sub(x,"*",userinput)
            userinput = result
        print result
        continue_or_not = raw_input("Do you want continue? Please input y/n. Any other inputs will be taken as y.\n")
        if continue_or_not.lower() == 'n':
            break
發佈了66 篇原創文章 · 獲贊 14 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章