Я прошел курс «Автоматизация скучных вещей» Python. Один практический проект требует, чтобы отрывок текста в txt-файле был изменен в соответствии с некоторыми пользовательскими данными.
Моя попытка приведена ниже, но мой образ мышления по-прежнему является очень долгим способом выполнения работы. Я не считаю, что мой код является наиболее эффективным методом pythoni c.
Есть ли лучший, более эффективный способ сделать это?
Любые отзывы приветствуются (я оставил мои заметки в коде для наглядности).
Replace the words ADJECTIVE, NOUN, ADVERB and NOUN in a passage of text.
Use prompts to input the words to be used.
Print to sceen and save to file.
#Prompt user for the words to add
from pathlib import Path
file = open('Mad Libs.txt', 'w')
file.write('The ADJECTIVE panda walked to the NOUNONE and then VERB. A nearby NOUNTWO was unaffected
by these events.')
file.close()
print('Enter an adjective: ')
a = input()
print('Enter a noun: ')
nOne = input()
print('Enter a verb: ')
v = input()
print('Enter a noun: ')
nTwo = input()
#Open the file and split the passage into a list??
file = open('Mad Libs.txt')
text = file.read().split()
#Find words in file to be replaced.
aIndex = text.index('ADJECTIVE')
nOneIndex = text.index('NOUNONE')
vIndex = text.index('VERB.')
nTwoIndex = text.index('NOUNTWO')
#Replace each word with the inputs and close.
text[aIndex] = a
text[nOneIndex] = nOne
text[vIndex] = v+'.'
text[nTwoIndex] = nTwo
#Join text back to a readable passage and print to screen.
newText = " ".join(text)
print('\n\n')
print(newText)
#Print the new text to file.
file = open('Mad Libs.txt', 'a')
file.write('\n\n' + newText)
file.close()
Спасибо,
Стюарт