2016年1月30日土曜日

開発環境

  • OS X El Capitan - Apple (OS)
  • Emacs (Text Editor)
  • Python 3.5 (プログラミング言語)

Automate the Boring Stuff with Python (Al Sweigart (著)、No Starch Press)のPart 2.(Automating Tasks)、Chapter 8.(Reading and Writing Files)、Practice Projects(Mad Libs)を取り組んでみる。

Practice Projects(Mad Libs)

コード(Emacs)

#!/usr/bin/env python3
#-*- coding: utf-8 -*-

with open('input.txt') as f:
    text = f.read()

adjective = input('Enter an adjective:\n')
text = text.replace('ADJECTIVE', adjective, 1)
noun = input('Enter an noun:\n')
text = text.replace('NOUN', noun, 1)
verb = input('Enter an VERB:\n')
text = text.replace('VERB', verb, 1)
noun = input('Enter an noun:\n')
text = text.replace('NOUN', noun, 1)

print(text, end='')
with open('out.txt', 'w') as f:
    print(text, file=f, end='')
    

入出力結果(Terminal, IPython)

$ cat input.txt
The ADJECTIVE pand walked to the NOUN and then VERB.
A nearyby NOUN was unaffected by these events.
$ ./madlibs.py
Enter an adjective:
silly
Enter an noun:
chandelier
Enter an VERB:
screamed
Enter an noun:
pickup truck
The silly pand walked to the chandelier and then screamed.
A nearyby pickup truck was unaffected by these events.
$ cat out.txt 
The silly pand walked to the chandelier and then screamed.
A nearyby pickup truck was unaffected by these events.
$ 

0 コメント:

コメントを投稿