在python中搜索特定单词后,将一个单词添加到文本文件中

时间:2018-08-30 11:42:44

标签: python data-extraction

我想读取一个文本文件并想要一个特定的单词,然后想要在其旁边附加其他单词。

例如:

我想在像John这样的文件中找到名字,然后想像John Smith这样在“ John”后面加上姓氏。

这是我到目前为止所写的代码。

usrinp = input("Enter name: ")

lines = []
with open('names.txt','rt') as in_file:
    for line in in_file:
        lines.append(line.rstrip('\n'))



    for element in lines:
        if usrinp in element is not -1:
            print(lines[0]+" Smith")
        print(element)

那是文本文件的样子:

My name is FirstName
My name is FirstName
My name is FirstName
FirstName is a asp developer
Java developer is FirstName
FirstName is a python developer

2 个答案:

答案 0 :(得分:0)

使用replace是一种方法。

输入文件(names.txt):

My name is John
My name is John
My name is John
John is a asp developer
Java developer is John
John is a python developer

脚本:

name = 'John'
last_name = 'Smith'

with open('names.txt','r') as names_file:
    content = names_file.read()
    new = content.replace(name, ' '.join([name, last_name]))

with open('new_names.txt','w') as new_names_file:
    new_names_file.write(new)

输出文件(new_names.txt):

My name is John Smith
My name is John Smith
My name is John Smith
John Smith is a asp developer
Java developer is John Smith
John Smith is a python developer

答案 1 :(得分:0)

“mymessagingservice_inbox_messagecount{environment="prod"}[30m]”