Hier ist mein Code. Ich bin sehr neu bei Python und bevor ich zum Bau von Werkzeugen überspringe, möchte ich die Grundlagen kennen. Ist das ein guter Code? Gibt es eine Möglichkeit, es zu verbessern? Heres die Sache, die die .replace() musste 4 mal verwendet werden. Gibt es eine Möglichkeit, ADJECTIVE, ADVERB, NOUN und VERB auf einmal durch Benutzereingaben zu ersetzen? Hinweis: Ich lese AUTOMATISIEREN DAS BOHREN MATERIAL MIT PYTHON praktische Programmierung für Anfänger insgesamt Seite: 195 Mad Libs. Auch ich bin auf Linux;)Gibt es eine Alternative zu .replace() in Python?
#!/usr/bin/env python
# Usage: ./mad_libs.py start
# This program finds any .txt document to look for instances of ADJECTIVE, ADVERB, NOUN, and VERB within the file.
# these instances will be replaced by user input
import sys, os, time
# This opens any .txt file within the current working directory
try:
if sys.argv[1].lower() == 'start':
for file in os.listdir('.'):
if file.endswith('.txt'):
print('Opening text file...')
time.sleep(5)
os.system('clear')
open_file = open(file, 'r')
read_open_file = open_file.read()
contents_of_the_file = str(read_open_file)
# If the user does not run ./mad_libs.py start print this and close the program
except IndexError:
print('''Usage: ./mad_libs.py start
This program grabs a text file in the current working directory. The text file must contain any of the
following; ADJECTIVE, ADVERB, NOUN, VERB in capital letters each. Any instances will be replaced with
user input.
''')
sys.exit()
# This asks the user for an adjective, adverb, noun, and verb
print('Give me an adjective')
ADJECTIVE = raw_input()
print('Give me an adverb')
ADVERB = raw_input()
print('Give me a noun')
NOUN = raw_input()
print('Give me a verb')
VERB = raw_input()
# Anything in the file containing ADJECTIVE, NOUN, ADVERB, and VERB will be replaced with user input
modification_to_file_1 = contents_of_the_file.replace('ADJECTIVE', ADJECTIVE)
modification_to_file_2 = modification_to_file_1.replace('NOUN', NOUN)
modification_to_file_3 = modification_to_file_2.replace('ADVERB', ADVERB)
final_text = modification_to_file_3.replace('VERB', VERB)
# Finished new content is printed to user
os.system('clear')
print(final_text)
sehr, sehr nett. schätze diesen Link und diesen Code! – wetw0rk