300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > python替换文本文件单词_Python:如何替换文本文件中一行的最后一个单词?

python替换文本文件单词_Python:如何替换文本文件中一行的最后一个单词?

时间:2019-04-17 07:57:21

相关推荐

python替换文本文件单词_Python:如何替换文本文件中一行的最后一个单词?

请检查这个,不是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)

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。