ここに私のコードです。私は非常にPythonの新しいと私はビルドツールにジャンプする前に、私は基本を知りたい。この良いコードですか?改善できる方法はありますか? .replace()を4回使用しなければならないことを強調します。ユーザー入力を使って、ADJECTIVE、ADVERB、NOUN、およびVERBを一度に置き換える方法はありますか?注:私は、初心者の皆さんのために、ボイリングスタンドをパイソンで自動翻訳しています:195 Mad Libs。また私はLinux上にいる);pythonに.replace()の代替手段がありますか?
#!/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)
非常に非常にいいです。そのリンクとそのコードを感謝! – wetw0rk