Help us understand the problem. What is going on with this article?

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

背景

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.]]
"""

反省

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

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away