2017-03-11 1 views
0

私はS.O.にこの質問についての2つの投稿があることを知っています。彼らは私の問題を解決する助けにはなりませんでした。私はアキュムレータを使用してテキストファイルの値を合計しようとしています。各行に数字がある場合、私のコードはファイル内の各行を表示します。間に空白があると、エラーメッセージが表示されます。私はそれが単純な見落としだと思うが、私はPythonには新しいので、私は何が間違っているのか分からない。Pythonでテキストファイルの値をどのように集計しますか?

マイコード:

def main(): 
    #Open a file named numbers.txt 
    numbers_file = open('numbers.txt','r') 
    #read the numbers on the file 
    number = numbers_file.readline() 

    while number != '': 
     #convert to integer 
     int_number = int(number) 
     #create accumulator 
     total = 0 
     #Accumulates a total number 
     total += int_number 
     #read the numbers on the file 
     number = numbers_file.readline() 
     #Print the data that was inside the file 
     print(total) 
    #Close the the numbers file 
    numbers_file.close() 

#Call the main function 
main() 
テキストファイル内の

入力:テキストファイル内

100 

200 

300 

400 

500 

Gives me error message: 
ValueError: invalid literal for int() with base 10: '\n' 

入力:

100 
200 
300 
400 
500 

Prints: 
100 
200 
300 
400 
500 

答えて

1

空白行をint()に変換できないため、空白行を除外する必要があります。これを行う一つのニシキヘビ(EAFP)の方法は、(これは黙っ以外の数の行を無視しますが)例外をキャッチして無視することです:

with open('numbers.txt','r') as numbers_file: 
    total = 0 
    for line in numbers_file: 
     try: 
      total += int(line) 
     except ValueError: 
      pass 
print(total) 

それとも、明示的に空の文字列を持っていないことをテストすることができます.strip()あなたの後にすべての空白(これはまだ非数値行のエラー、例えば'hello'ます):

with open('numbers.txt','r') as numbers_file: 
    total = 0 
    for line in numbers_file: 
     if line.strip(): 
      total += int(line) 
print(total) 

この第二の1は、ジェネレータ式のように書くことができます。

with open('numbers.txt','r') as numbers_file: 
    total = sum(int(line) for line in numbers_file if line.strip()) 
print(total) 
0

あなたはそれぞれ自分のアキュムレータに値0を割り当てます新しい値を追加する前に、ループを通過する時間。これは、毎回0に新しい値を追加することを意味します。つまり、新しい値を印刷するだけです。
ループの前に行total = 0を移動すると、期待通りに動作するはずです。

あなたがしたい場合は、少しこれをクリーンアップすることができます。

numbers_file = open('numbers.txt','r')  
total = 0 
for number in numbers_file: 
    if number: 
     int_number = int(number) 
     total += int_number 
     print(total) 
numbers_file.close() 

は、最初のパスになります。 if numberのチェックでは、numberに「真実」の値が含まれている場合はTrueを返します。この場合、空の行に当たった場合に発生します。

+0

'number'はまだ空行に改行' \ n'を含んでいるので空ではありません。 – AChampion

0

こんにちは、あなたは '新しい行のシンボル'である\nを削除することができません。 数値に変換できるリテラルのみを確実に取得するには、他の文字を削除する必要があります。

a = '100\ntest' 
print(a.isnumeric()) 
a = '103478' 
print(a.isnumeric()) 

数字に変換できない文字があるかどうかをテストできます。 文字列を簡単に操作するための正規表現パッケージ。

this stack overflow threatを参照してください。

import re 
a = jkfads1000ki' 
re.sub('\D','',a) 
'1000' 

rethe Python docsを参照してください。

関連する問題