Replacing lines of output with custom message

和自甴很熟 提交于 2019-12-14 02:23:54

问题


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 

回答1:


This could work.

print('Please enter a taboo word and a filename, separated by a comma: ')
word, filename = input('>').split(",")
file = open(filename)
line = file.readline()
while line:
    print(line.replace(word, "LINE REDACTED"))
    line = file.readline()
file.close()

Hope it helps!




回答2:


You don't need the while loop nor the try block:

print('Please enter a taboo word and a filename, separated by a comma: ')
filename = input('>')
info = filename.split(',')

with open(info[1], 'r') as f:
    for line in f:
        if info[0] in line:
            print('LINE REDACTED')
        else:
            print(line)



回答3:


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='')


来源:https://stackoverflow.com/questions/28885457/replacing-lines-of-output-with-custom-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!