Python入门试题(CLASS_2)

创建文本文档写入内容并过滤敏感词

创建文档写入内容

需求:传入参数name与msg就可以控制在桌面写入的文件名称和内容的函数text_create,并且如果桌面没有这个可以写入的文件时,就创建一个写入。

def text_create(name,msg):
    desktop_path='C:/Users/name/Desktop/'
    #文件所在位置
    full_path=desktop_path+name+'.txt'
    #根据参数name指定文件名
    file=open(full_path,'w')
    #open(路径,打开方式)打开对应路径的文件
    file.write(msg)
    #write()在文件写入输入内容
    file.close()
    #close()关闭文件
    print('Done')
text_create('hello','hello world')    

敏感词过滤

需求:定义一个text_filter函数,传入参数word,cencored_word,changed_word实现过滤,敏感词cencored_word默认为‘lame’,替换词默认为‘Awesome’。

def text_filter(word,cencorde_word='lame',changed_word='Awesome'):
    return word.replace(cencorde_word,changed_word)
text_filter('Python is lame')
#传入word值

两个函数合并

创建一个名为text_censored_create函数,功能是在桌面上创建一个文本可以在其中输入文字,但是如果信息中含有敏感词的话将会被默认过滤后写入文件。

def censored_text_create(name,msg):
    clean_msg=text_filter(msg)
    text_create(name,msg)
censored_text_create('Try','lame!lame!lame!')

猜你喜欢

转载自blog.csdn.net/weixin_42289215/article/details/82718370