9月 252020
 
#自定义函数,指定两个默认参数
def create_file(filename, content, censored_content = 'lame', changed_content = 'Awesome'):
    full_path = 'C:/Users/harveymei/Desktop/'
    full_name = full_path + filename + '.txt'
    file = open(full_name,'w')
    #在写入操作时对传入内容参数进行匹配替换
    #file.write(content)
    file.write(content.replace(censored_content, changed_content))
    file.close()
    print('Done')

#调用函数创建文件,传入文件名参数及内容参数
create_file('helloworld', 'Python is lame!')
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
Done
PS C:\Users\harveymei> type .\Desktop\helloworld.txt
Python is Awesome!     
PS C:\Users\harveymei> 
#自定义函数,敏感词删剪替换
#指定参数censored_word和changed_word默认值
def text_filter(word, censored_word = 'lame', changed_word = 'Awesome'):
    #替换word中匹配的censored_word为changed_word
    #返回replace()处理后的结果
    return word.replace(censored_word, changed_word)

#自定义函数,写文件
def create_file(filename, content):
    full_path = 'C:/Users/harveymei/Desktop/'
    full_name = full_path + filename + '.txt'
    file = open(full_name,'w')
    file.write(content)
    file.close()

#自定义函数,调用以上两个函数,分别替换关键词,写文件
def censored_create_file(filename, content):
    #调用敏感词删剪函数text_filter()先替换内容
    clean_content = text_filter(content)
    #调用生成文件函数create_file(),使用替换过的内容变量clean_content作为参数传入
    create_file(filename, clean_content)

#调用函数创建文件,传入文件名参数及内容参数
censored_create_file('helloworld', 'Python is lame!')
print('Done')
PS C:\Users\harveymei> & C:/Users/harveymei/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harveymei/hello.py
Done
PS C:\Users\harveymei> type .\Desktop\helloworld.txt
Python is Awesome!     
PS C:\Users\harveymei> 

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据