请检查这个,不是100%Python,是更多的概述file_text = '''I'm at the shop with Bill.
I'm at the shop with Sarah.
I'm at the shop with nobody.
I'm at the shop with Cameron.
I'm at the shop with nobody.'''
def rep_last_word_line(textin, search_for, replace_with, line_nr):
if (isinstance(textin,str)):
textin = textin.splitlines()
else:
# remove enline from all lines - just in case
textin = [ln.replace('\n', ' ').replace('\r', '') for ln in textin]
if (textin[line_nr] != None):
line = textin[line_nr].replace('\n', ' ').replace('\r', '')
splited_line = line.split()
last_word = splited_line[-1]
if (last_word[0:len(search_for)] == search_for):
splited_line[-1] = last_word.replace(search_for,replace_with)
textin[line_nr] = ' '.join(splited_line)
return '\r\n'.join(textin)
print rep_last_word_line(file_text,'nobody','Steve',2)
print '='*80
print rep_last_word_line(file_text,'nobody','Steve',4)
print '='*80
# read content from file
f = open('in.txt','r')
# file_text = f.read().splitlines() # read text and then use str.splitlines to split line withoud endline character
file_text = f.readlines() # this will keep the endline character
print rep_last_word_line(file_text,'nobody','Steve',2)