用自定义消息替换输出行

时间:2015-03-05 18:51:09

标签: python python-3.x python-3.4

我正在尝试构建一个函数,要求用户输入禁忌词然后输入文件名。然后,该脚本应该打开文件并逐行打印,但是将其中包含禁忌词的任何行替换为审查消息,例如 LINE删除 。我只是坚持最后一部分,即添加审查信息。这就是我到目前为止所做的:

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 

3 个答案:

答案 0 :(得分:0)

这可行。

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()

希望它有所帮助!

答案 1 :(得分:0)

您不需要while循环或try块:

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)

答案 2 :(得分:0)

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