Python ファイル読み込みと配列

やりたいこと : データファイル data.txt があって、そのデータを配列にする

 

data.txt

--------------

3

9

1

2

5

---------------

 

コード:

---------------

f.open('data.txt') #ファイルを開く

list = [] #配列を宣言

list = f.read() #ファイルの中身を配列に格納

print(list) #配列を表示

print(len(list)) #配列の長さを表示

print(list[1]) #配列の2要素目を表示(配列は0からスタート)

f.close() #ファイルを閉じる

-----------------

 

結果:

3

9

1

2

5

5 #配列の要素数

9 #配列2要素目の値

 

ちなみに、ファイルの中身を行ごとに取り出したいときは、

f.readlines()

 

awk 基本

  • awkコマンドの書き方

% awk '{コマンド}' ファイル名

 

ファイルtest.txtを用いて色々やってみる

test.txtの中身

-------------------

11 12 13 14 15

21 22 23 24 25

31 32 33 34 35

-------------------

 

  • awkの基本
    • 区切り文字
      空白や,など
    • 列 
      ファイルの中身は区切り文字によって列に分解される
      列は、$1, $2,..で1列目, 2列目と指定できる

    • 行の指定は、NR==[行番号]でできる

 

  • 基本コマンド
    • print          ←ファイルの中身を表示する
      % awk '{print'} test.txt

      11 12 13 14 15

      21 22 23 24 25

      31 32 33 34 35
      % awk'{print $1, $3}' test.txt
      11 13
      21 23
      31 33

    • printf
      % awk '{printf "%s ++ %s", $1, $3}' test.txt
      11++1321++2331++33  ←改行なく表示される
      % awk '{printf "%s ++ %s¥n", $1, $3}' test.txt
      11++13
      21++23
      31++33         ←改行された

 

 

Latexにpngを入れる

Latexではepsに変換しないと貼れないとあったが、

dvipdfmxを使うことでjpgやpngをそのまま貼り付けられる

 

\usepackage[dvipdfmx]{graphicx}

\begin{figure}[!tp]
  \centering
  \includegraphics[width=0.7\columnwidth]{image.png}
  \caption{caption}
  \label{fig:image}
\end{figure}

 

AttributeError: partially initialized module has no attribute…

Pythonで次のようなエラーが起こった時

AttributeError: partially initialized module has no attribute…

 

これは実行しているPythonのコードファイル名が、モジュール名と同じ時に起こる

 

解決方法:

ファイル名を変える

それでもエラーが起こるときは、一度ターミナルを終了して、再度立ち上げれば解決する

Typeerror: can't concat int to bytes

Pythonで次のようなエラーが起こった時

Typeerror: can't concat int to bytes

 

これはエラーが起こっている変数を、bytesに変換すればいいので、例えば

bytes()メソッドを使って変換すればいい

例:test = a + b + bytes(c)

MacOS gnuplot 導入とやり方

Homebrewを使ったインストール

%brew install gnuplot

 

 

インストール後

%gnuplot

 

G N U P L O T

Version 5.4 patchlevel 2    last modified 2021-06-01 

 

Copyright (C) 1986-1993, 1998, 2004, 2007-2021

Thomas Williams, Colin Kelley and many others

 

gnuplot home:     http://www.gnuplot.info

faq, bugs, etc:   type "help FAQ"

immediate help:   type "help"  (plot window: hit 'h')

 

Terminal type is now 'qt'

gnuplot>

となる

Terminal type is now 'unknown’となっていたら、書けない

gnuplot>plot sin(x)

gnuplot>plot x*5

 

 

 

直近に消したものはControl-Pで戻せる