2016-03-27 36 views
-2

ファイルmbox-short.txtを開き、1行ずつ読み込みます。あなたは次の行LIKE「から」で始まる行を見つけた場合:Pythonエラー:TypeError: 'int'オブジェクトが呼び出し可能ではありません

From [email protected] Sat Jan 5 09:14:16 2008 

あなたはスプリットを()を使用して、ラインから解析し、(ラインで人のすなわち全体のアドレスを2番目の単語を出力します誰がメッセージを送ったか)。そして、最後にカウントを表示します。

ヒント: 'From:'で始まる行は含めないでください。 MBOX-short.txtファイルの

リンク: http://www.pythonlearn.com/code/mbox-short.txt

fopen = raw_input('Enter the file name you want to open: ') 
fname = open(fopen) 
line = 0 
count = 0 
pieces = 0 
email = list() 
for line in fname: 
    lines = line.rstrip() 
    if not line.startswith('From '): 
     continue 
    pieces = line.split() 
    print pieces[1] 
print 'There were' ,count(pieces[1]), 'lines in the file with From as the first word 

は私が最後の印刷メッセージまで、正しい出力を得ることができました。

実行:

Enter the file name you want to open: mbox-short.txt 

[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 
[email protected] 

Traceback (most recent call last): 
print 'There were' ,count(pieces[1]), 'lines in the file with From as the first word' 

TypeError: 'int' object is not callable 

私は、このトレースバックを取得しています理由はわかりません。

+1

スクリプトの先頭には、 'count = 0'があります。これは呼び出し可能ではなく、function/class/etcです。あなたはそれが何をすると思いましたか? – Reti43

+0

'count'は変数であり、関数ではありません。私はあなたがちょうど使用すると思います: 'print '最初の単語から'ファイル'の中に 'pieces [1]、' linesがあります.'それはうまくいくはずです... – thefoxrocks

+0

他の答えは 'count'は関数ではないので、なぜそれが動作すると思うのか分かりません。 –

答えて

0

:これに

print 'There were' ,count(pieces[1]), 

を、countはaとして表示されていません関数ではなく、intです。 pieces[1]にそれを渡すことはできず、魔法的にそれ自身をインクリメントすることを期待する。

このようにカウントしたい場合は、ファイルをループしながらカウントを更新するだけです。

fopen = raw_input('Enter the file name you want to open: ') 
fname = open(fopen) 
line = 0 # unnecessary 
count = 0 
pieces = 0 # also unnecessary 
email = list() # also unnecessary 
for line in fname: 
    lines = line.rstrip() 
    if not line.startswith('From '): 
     continue 
    pieces = line.split() 
    print pieces[1] 
    count = count + 1 # increment here - counts number of lines in file 
print 'There were', count, 'lines in the file with From as the first word 
+1

ところで、出力に余分なスペースを追加しています。 – TigerhawkT3

+0

編集されました。ありがとう!しばらくの間、私は 'print'の厄介な文章を使っていませんでした... –

+1

これはPython 3でも同じように起こります。デフォルトのセパレータはスペースです。 – TigerhawkT3

0

'int' object is not callablecount = 0、次にcount(pieces[1])です。あなたは整数を持っており、あなたはそれを呼び出しています。この後:

pieces = line.split() 
print pieces[1] 

は、この追加:

count += 1 

をしてから、この変更:問題のコメントが述べたように

print 'There were', count, 
+0

私の問題の大部分を手伝ってくれてありがとうございました。 – Roy

関連する問題