第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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章