Добавить текстовое слово в текстовый файл после поиска конкретного слова в Python - PullRequest
0 голосов
/ 30 августа 2018

Я хочу прочитать текстовый файл и хочу к определенному слову, а затем хочу добавить другое слово рядом с ним.

Например:

Я хочу найти имя в файле, подобном Джону, а затем добавить фамилию с «Джоном», как Джон Смит.

Вот код, который я написал до сих пор.

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 голосов
/ 30 августа 2018
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 
0 голосов
/ 30 августа 2018

Использование 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
...