LoginSignup
1
1

More than 3 years have passed since last update.

Python テキスト読み込み 複数行と一行の場合

Last updated at Posted at 2019-12-03

背景

YOLOv3のコードでPythonを勉強したとき、メモとして記録しておきたかった。
各内容ができ次第、アップします。

テキスト読み込み

今回扱うのはテキスト内容は複数行の場合と一行の場合である。

サンプルテキスト:複数行

coco_classes.txt
person
bicycle
car
motorbike
aeroplane

サンプルコード:複数行

readlines_.py
import os
classes_path = 'model_data/coco_classes.txt'
#ホームディレクトリに変更
classes_path = os.path.expanduser(classes_path)
with open(classes_path) as f:
#テキストを文字列+改行として、1つのリストにする
    class_names = f.readlines()

# テキスト内のn行目の値をcに入れて、改行を削除
for c in class_names:
    c = c.strip()
    print(c)

サンプルテキスト:一行

tiny_yolo_anchors.txt
10,14,  23,27,  37,58,  81,82,  135,169,  344,319

サンプルコード:一行

readline_.py
import os
anchors_path= 'model_data/tiny_yolo_anchors.txt'
#ホームディレクトリに変更
anchors_path= os.path.expanduser(classes_path)
with open(anchors_path) as f:
#テキストを文字列+改行として、1つのリストにする
    anchors_path= f.readline()

# テキスト内の','で区切った値のn番目の値をxに入れて、float型に変更
for x in anchors.split(','):
    x = float(x)
    print(x)

#上記の処理に付随
anchors = [float(x) for x in anchors.split(',')]

さらに文字列で遊んでみた

play_with_anchors_value.py
import os
import numpy as np
anchors_path= 'model_data/tiny_yolo_anchors.txt'
with open(anchors_path) as f:
    anchors_path= f.readline()

print(anchors_path)
#10,14,  23,27,  37,58,  81,82,  135,169,  344,319

anchors = [float(x) for x in anchors.split(',')]
print(anchors_path)
#[10.0, 14.0, 23.0, 27.0, 37.0, 58.0, 81.0, 82.0, 135.0, 169.0, 344.0, 319.0]

anchors = np.array(anchors).reshape(-1, 2)#座標の2列に整える、-1は補正扱い
print(anchors_path)
"""
[[ 10.  14.]
 [ 23.  27.]
 [ 37.  58.]
 [ 81.  82.]
 [135. 169.]
 [344. 319.]]
"""

反省

コード解読は勉強になる(かもしれない)。

1
1
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
1
1