2016-04-25 27 views
-1

空の行を除いた( '/ dir' /)のcsvファイルの長さを取得する必要があります。 私はこれを試してみました:私は私が好きな出力を得る複数のcsvファイルの行を数えて空白行をスキップ

import os, csv, itertools, glob 

#To filer the empty lines 
def filterfalse(predicate, iterable): 
    # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 
    if predicate is None: 
     predicate = bool 
    for x in iterable: 
     if not predicate(x): 
      yield x 

#To read each file in '/dir/', compute the length and write the output 'count.csv' 
with open('count.csv', 'w') as out: 
    file_list = glob.glob('/dir/*') 
    for file_name in file_list: 
     with open(file_name, 'r') as f: 
       filt_f1 = filterfalse(lambda line: line.startswith('\n'), f) 
       count = sum(1 for line in f if (filt_f1)) 
       out.write('{c} {f}\n'.format(c = count, f = file_name)) 

が、残念ながら(「//DIR」内)の各ファイルの長さが空の行が含まれています。空の行は、私から来ている場所を確認するには

file.txtとしてfile.csvを読んで、それは次のようになります。

*text,favorited,favoriteCount,... 
"Retweeted user (@user):... 
'empty row' 
Do Operators...* 

答えて

1

私はパンダを使用することをお勧めします。

import pandas 

# Reads csv file and converts it to pandas dataframe. 
df = pandas.read_csv('myfile.csv') 

# Removes rows where data is missing. 
df.dropna(inplace=True) 

# Gets length of dataframe and displays it. 
df_length = df.count + 1 
print('The length of the CSV file is', df_length) 

ドキュメント:http://pandas.pydata.org/pandas-docs/version/0.18.0/

1

あなたfilterfalse()機能が正しく実行されます。 正確には標準ライブラリitertoolsモジュールのifilterfalseと同じものなので、自分で書くのではなく、なぜテストしてデバッグしたのかが不明です。 (多くの場合、C言語で書かれているので、ビルトインも高速です。)

generator functionを正しく使用していないという問題があります。

  1. generator objectを返すので、一つは、それが潜在的にyieldfor line in filt_f1ようなコードを使用します複数の値を反復する必要があります。

  2. 与えられた述語関数の引数は、空白やタブのような他の先行する空白文字を含む行を正しく処理しません。 - lambdaを渡すと、それらのケースを処理するために変更する必要があります。

以下のコードには、これらの変更が加えられています。

import os, csv, itertools, glob 

#To filter the empty lines 
def filterfalse(predicate, iterable): 
    # filterfalse(lambda x: x%2, range(10)) --> 0 2 4 6 8 
    if predicate is None: 
     predicate = bool 
    for x in iterable: 
     if not predicate(x): 
      yield x 

#To read each file in '/dir/', compute the length and write the output 'count.csv' 
with open('count.csv', 'w') as out: 
    file_list = glob.glob('/dir/*') 
    for file_name in file_list: 
     with open(file_name, 'r') as f: 
      filt_f1 = filterfalse(lambda line: not line.strip(), f) # CHANGED 
      count = sum(1 for line in filt_f1) # CHANGED 
      out.write('{c} {f}\n'.format(c=count, f=file_name)) 
+0

ありがとうございます。これは部分的に機能します(つまり、まだ空白行があります) – user2278505

関連する問題