0

テキストファイルをインポートした後に基本的なグラフを出力する簡単なプログラムを書いています。次のエラーが表示されます。

Traceback (most recent call last):
  File "C:\Users\Chris1\Desktop\attempt2\ex1.py", line 13, in <module>
    x.append(int(xAndY[0]))
ValueError: invalid literal for int() with base 10: '270.286'

私のpythonコードは次のようになります:

    import matplotlib.pyplot as plt

x = []
y = []

readFile = open ('temp.txt', 'r')

sepFile = readFile.read().split('\n')
readFile.close()

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    x.append(int(xAndY[0]))
    y.append(int(xAndY[1]))

print x
print y



plt.plot(x, y)

plt.title('example 1')
plt.xlabel('D')
plt.ylabel('Frequency')

plt.show()    

テキスト ファイルのスニペットは次のようになります。

270.286,4.353,16968.982,1903.115
38.934,68.608,16909.727,1930.394    
190.989,1.148,16785.367,1969.925         

問題は軽微ですが、自分で解決できないようです ありがとう

4

2 に答える 2

0

解決策

浮動小数点値を整数に変換する場合は、単に変更します

x.append(int(xAndY[0]))
y.append(int(xAndY[1]))

x.append(int(float(xAndY[0])))
y.append(int(float(xAndY[1])))

ここに画像の説明を入力

エラーが発生する理由

組み込み関数intが float の文字列表現を引数として受け入れないため、エラーが発生します。ドキュメントから:

int ( x=0 )
int ( x, base=10 )
... x
が数値でない 場合、または base が指定されている場合、 xは基数ベースの整数リテラルを表す文字列または Unicode オブジェクトでなければなりません。オプションで、リテラルの前に + または - (間にスペースを入れない) を付け、空白で囲むことができます。基数 n のリテラルは、0 から n-1 の数字で構成され、a から z (または A から Z) は 10 から 35 の値を持ちます。

あなたの場合(xは数値ではなく、浮動小数点数の文字列表現です)、これは関数が値を変換する方法を知らないことを意味します。これは、base=10では、引数に数字 [0-9] のみを含めることができるためです。つまり、.(ドット) を含めることはできません。これは、文字列が float の表現にならないことを意味します。


より良い解決策

を調べることをお勧めします。numpy.loadtxtこれは使いやすい方法です。

x, y = np.loadtxt('temp.txt',     # Load values from the file 'temp.txt'
                  dtype=int,      # Convert values to integers
                  delimiter=',',  # Comma separated values
                  unpack=True,    # Unpack to several variables
                  usecols=(0,1))  # Use only columns 0 and 1

修正後のコードxと同じリストを生成します。y

この変更により、コードを次のように削減できます。

import matplotlib.pyplot as plt
import numpy as np

x, y = np.loadtxt('temp.txt', dtype=int, delimiter=',',
                  unpack=True, usecols=(0,1))

plt.plot(x, y)

plt.title('example 1')
plt.xlabel('D')
plt.ylabel('Frequency')

plt.show()
于 2013-07-19T14:19:58.233 に答える