用自定义消息替换输出行 [英] Replacing lines of output with custom message

查看:55
本文介绍了用自定义消息替换输出行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个函数,要求用户输入一个禁忌词,然后输入一个文件名.然后脚本应打开文件并逐行打印,但将任何包含禁忌词的行替换为审查消息,例如 LINE REDACTED.我只是停留在添加审查信息的最后一部分.这是我目前所拥有的:

I am trying to build a function that asks the user to enter a taboo word and then a filename. The script should then open the file and print it line by line, but replacing any line that has the taboo word in it with a censorship message such as LINE REDACTED. I'm just stuck on the last part which is adding a censorship message. This is what I have so far:

print('Please enter a taboo word and a filename, separated by a comma: ')
filename = input('>')
while True:
    try:
        file = open(filename)
        line = file.readline()
        while line != "":
            print(line)
        file.close()
        break 

推荐答案

print('Please enter a taboo word and a filename, separated by a comma: ')
taboo, filename = input('>').split(',')
with open(filename) as file:
    for line in file:
        print(line if taboo not in line else 'LINE REDACTED\n', end='')

这篇关于用自定义消息替换输出行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆