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

在python中搜索特定单词后,将文本单词附加到文本文件中,python,data-extraction,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'))

我想读一个文本文件,想读一个特定的单词,然后想在它旁边附加一些其他单词

例如:

我想在像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

使用
replace
是一种方法

输入文件(names.txt):

我叫约翰
我叫约翰
我叫约翰
John是一名asp开发人员
Java开发人员是John
John是python开发人员
脚本:

输出文件(new_names.txt):

我叫约翰·史密斯
我叫约翰·史密斯
我叫约翰·史密斯
约翰·史密斯是一名asp开发人员
Java开发人员是John Smith
John Smith是python开发人员

使用
replace
是一种方法

输入文件(names.txt):

我叫约翰
我叫约翰
我叫约翰
John是一名asp开发人员
Java开发人员是John
John是python开发人员
脚本:

输出文件(new_names.txt):

我叫约翰·史密斯
我叫约翰·史密斯
我叫约翰·史密斯
约翰·史密斯是一名asp开发人员
Java开发人员是John Smith
John Smith是python开发人员
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)
search_string = 'john'
file_content = open(file_path,'r+')
lines = []
flag = 0
for line in file_content:
    line = line.lower()
    stripped_line = line
    if search_string in line:
        flag = 1
        stripped_line = line.strip('\n')+' '+'smith \n'    
    lines.append(stripped_line)
file_content.close()
if(flag == 1):
    file_content = open(file_path,'w')
    file_content.writelines(lines)
    file_content.close()

**OUTPUT**

My name is FirstName

My name is FirstName

My name is FirstName

FirstName is a asp developer

Java developer is john smith

FirstName is a developer