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

时间:2015-05-01 12:47:14

标签: python

如何从已加载到Python中的文本文件的所有行替换特定行的最后一个单词?我知道如果我想以列表的形式访问它,我会使用[-1]作为特定行,但我不知道如何将其作为字符串。文本文件的示例是:

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.

3 个答案:

答案 0 :(得分:2)

如果您想要更强大的编辑选项,Regex是您的朋友。

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

答案 1 :(得分:-1)

假设您有一个文件" example.txt":

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

(编辑:修正了一个错误......假设是第3行,他的意思是人的风格计数而不是第0个索引)

(注意,with行返回一个文件对象,即使例如myfile的长度小于3,它也会自动关闭;这个文件对象还提供了一个迭代器,然后将其转换为直接列表,以便您可以选择特定的一行。)

答案 2 :(得分:-1)

如果您有空行,您可能需要尝试splitlines()

>> import tldextract
>> tldextract.extract("http://lol1.domain.com:8888/some/page"
ExtractResult(subdomain='lol1', domain='domain', suffix='com')
>> tldextract.extract("http://sub.lol1.domain.com:8888/some/page"
ExtractResult(subdomain='sub.lol1', domain='domain', suffix='com')
>> urlparse.urlparse("http://sub.lol1.domain.com:8888/some/page")
ParseResult(scheme='http', netloc='sub.lol1.domain.com:8888', path='/some/page', params='', query='', fragment='')

请注意,您的更改现在位于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) 而不是lines,因此如果您希望更改仍然存在,则您必须写出your_text而不是

lines