LoginSignup
0
0

More than 3 years have passed since last update.

Colaboratoryでセルをファイル出力する

Posted at

Colaboratory セル ファイル 出力でググっても出てこなかったので。

元ネタ: Cell magics@ipython

やり方

yesno.py
%%writefile yesno.py
#!/usr/bin/env python

import re

def main():
  check=input('YesかNoを入力してください :')
  print(YN(check))

def YN(string):
  if re.match('(?i)ye?s?',string):
    return 'YESです'
  elif re.match('(?i)no?',string):
    return 'NOです'
  else: return 'Yes/Noじゃないよ'

if __name__ == '__main__':
  main()

%%writefile yesno.pyがコマンド

!cat -n yesno.pyで確認すると

 1  #!/usr/bin/env python
 2  
 3  import re
 4  
 5  def main():
 6    check=input('YesかNoを入力してください :')
 7    print(YN(check))
 8  
 9  def YN(string):
10    if re.match('(?i)ye?s?',string):
11      return 'YESです'
12    elif re.match('(?i)no?',string):
13      return 'NOです'
14    else: return 'Yes/Noじゃないよ'
15  
16  if __name__ == '__main__':
17    main()

コマンドの直後からファイル出力されるので、シバンを記述する場合は気を付ける。

これにより

check.py
import yesno

if yesno.YN(('Yes')) == 'YESです': print('Yeah')

結果: Yeah

と使えるようになる。

まとめ

Pythonの勉強をColaboratoryでやっているとローカルファイルを元に書いてある課題をどうやってやるのか困る時があります。

Pythonでファイルをダウンロードすると合わせて使うと、大体はColaboratoryでできると思います。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0