0

私は次のcsvファイルを持っています:

hindex
1
2
2
6
3
3
3
2
2

行を読み取ってその値を確認しようとしていますが、次のエラーが発生します。

ValueError: invalid literal for int() with base 10: 'hindex'

コードは次のとおりです。

cr = csv.reader(open('C:\\Users\\chatterjees\\Desktop\\data\\topic_hindex.csv', "rb"))
for row in cr:
    x=row[0]
    if(int(x)<=10):
        print x

私のコードの何が問題になっていますか?

4

7 に答える 7

4

行1をスキップする必要があります。ファイルからintに列ヘッダーを解析しようとしていますが、char文字列であるため、窒息して死んでいます。

于 2012-04-17T14:28:39.787 に答える
4

コードは、を含むファイル内のすべての行を処理しようとしますhindex。この文字列を、ValueError:をスローするintに変換しようとしています。

(ヘッダーを含む)最初の行をスキップするには、次のことを試してください。

cr = csv.reader(open('C:\\Users\\chatterjees\\Desktop\\data\\topic_hindex.csv', "rb"))
for row in cr[1:]:
    x=row[0]
    if(int(x)<=10):
        print x
于 2012-04-17T14:29:27.987 に答える
4

.csvの最初の行には、intに変換できないものが含まれているため、

    if(int(x)<=10):

ValueErrorで失敗します。(式を()で囲む必要はまったくありません。)

次のように、.csvの最初の行をスキップするか int(x) 、try/catchブロックにラップすることができます。

for row in cr:
    x=row[0]
    try:
        x=int(x)
    except ValueError: # x cannot be converted to int
        continue       # so we skip this row
    if x<=10:  # no need for parens here
        print x

例外とその処理について詳しくは、http://docs.python.org/tutorial/errors.htmlをご覧ください。

于 2012-04-17T14:31:56.840 に答える
2

最初の行を整数に変換することはできません。try exceptブロックを使用すると、最初の行のようにすべての行をスキップできます。

cr = csv.reader(open('C:\\Users\\chatterjees\\Desktop\\data\\topic_hindex.csv', "rb"))
for row in cr:
  x=row[0]
  try:
    if int(x) <= 10:
      print x
  except ValueError:
    pass
于 2012-04-17T14:30:14.937 に答える
2

ヘッダー行をスキップしてデータを適切な辞書形式で取得するcsv.DictReaderのが本当に最も簡単な方法であるため、誰も言及していません。

import csv
with open('C:\\Users\\chatterjees\\Desktop\\data\\topic_hindex.csv', "rb") as f:
    cr = csv.DictReader(f)
    for row in cr:
        x = row['hindex']
        if int(x) <= 10:
            print x
于 2012-10-06T07:24:22.117 に答える
1

これは、最初の行と最初の行のみをスキップし、ValueError他の行に数値以外の値が含まれている場合に失敗するソリューションです。これは、enumerate()処理された行数のカウントを保持する組み込み関数を使用して行われます。withさらに、ステートメントの使用が完了すると、入力ファイルが適切に閉じられます。

import csv
with open('C:\\Users\\chatterjees\\Desktop\\data\\topic_hindex.csv', 'rb') as csvFile:
    for rowNumber, row in enumerate(csv.reader(csvFile)):
        if rowNumber > 0:
            x = row[0]
            if int(x) <= 10:
                print x
于 2012-10-06T07:08:51.080 に答える
1

ここにもう1つ選択肢があります。このタスクも簡単に処理できるラッパーライブラリを作成しました。次のスクリプトがあるディレクトリの「topic_hindex.csv」という名前のファイルにデータを保存したとします。

import pyexcel


r = pyexcel.SeriesReader("topic_hindex.csv")
for row in r.rows():
    x = row[0]
    if x <= 10:
        print x

または、フィルターを使用することもできます。

import pyexcel


r = pyexcel.SeriesReader("topic_hindex.csv")
eval_func = lambda row: row[0] <= 10
r.filter(pyexcel.RowValueFilter(eval_func))
for row in r.rows():
    print row[0]
于 2014-09-14T20:26:10.810 に答える