简体   繁体   中英

Python: How to replace the last word of a line from a text file?

How would I go about replacing the last word of a specific line from all the lines of a text file that has been loaded into Python? I know that if I wanted to access it as a list I'd use [-1] for the specific line, but I don't know how to do it as a string. An example of the text file is:

A I'm at the shop with Bill.
B I'm at the shop with Sarah. 
C I'm at the shop with nobody. 
D I'm at the shop with Cameron.

If you want a more powerful editing option, Regex is your friend.

import re
pattern = re.compile(r'\w*(\W*)$')  # Matches the last word, and captures any remaining non-word characters
                                    # so we don't lose punctuation. This will includes newline chars.

line_num = 2 # The line number we want to operate on.
new_name = 'Steve' # Who are we at the shops with? Not Allan.

with open('shopping_friends.txt') as f:
    lines = f.readlines()
    lines[line_num] = re.sub(pattern, new_name + r'\1', lines[line_num]) 
    # substitue the last word for your friend's name, keeping punctuation after it.
    # Now do something with your modified data here

please check this , is not 100% pythonic, is more for an overview

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) 

Assuming you have a file "example.txt":

with open("example.txt") as myfile:
   mylines = list(myfile)
   lastword = mylines[2].split()[-1]
   mylines[2] = mylines[2].replace(lastword,"Steve.") 

(Edit: fixed off by one error... assuming by 3rd line, he means human style counting rather than zeroth-indexed)

(Note that the with line returns a file object which will be automatically closed even if for example the length of myfile is less than 3; this file object also provides an iterator which then gets converted into a straight list so you can pick a specific line.)

If you have blank lines, you might want to try splitlines()

lines = your_text.splitlines()
lastword = lines[line_to_replace].split()[-1]
lines[line_to_replace] = lines[line_to_replace].replace(lastword, word_to_replace_with) 

keep in mind that your changes are in lines now and not your_text so if you want your changes to persist, you'll have to write out lines instead

with open('shops.txt', 'w') as s:
    for l in lines:
        s.write(l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM