问题
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