2016-10-18 14 views
2

この問題の基本的な概要は、re.findall()を使用して整数を検索し、正規表現[0-9]+を探して、抽出された文字列を整数に変換して整数を合計します。正規表現を使用してデータを抽出する:Python

リストを追加する際に問題が見つかりました。私の下のコードから、それはちょうどラインの最初の(0)インデックスを追加しています。私を助けてください。ありがとうございました。

import re 
hand = open ('a.txt') 
lst = list() 
for line in hand: 
    line = line.rstrip() 
    stuff = re.findall('[0-9]+', line) 
    if len(stuff)!= 1 : continue 
    num = int (stuff[0]) 
    lst.append(num) 
print sum(lst) 
+0

「a.txt」の行のいくつかを表示できますか? – mitoRibo

+0

お返事ありがとうございます。下のリンクは、ファイル内のテキスト全体にリダイレクトされます。 http://python-data.dr-chuck.net/regex_sum_325354.txt –

答えて

0

txtファイル全体を含めていただきありがとうございます。あなたの主な問題は、stuffにゼロのものがあった場合、2,3などがあった場合にスキップしていたif len(stuff)...行にありました。 stuffの長さのリストを1つだけ保管していました。私はコードにコメントを付けましたが、何か不明な点があれば質問してください。

import re 
hand = open ('a.txt') 
str_num_lst = list() 
for line in hand: 
    line = line.rstrip() 
    stuff = re.findall('[0-9]+', line) 
    #If we didn't find anything on this line then continue 
    if len(stuff) == 0: continue 
    #if len(stuff)!= 1: continue #<-- This line was wrong as it skip lists with more than 1 element 

    #If we did find something, stuff will be a list of string: 
    #(i.e. stuff = ['9607', '4292', '4498'] or stuff = ['4563']) 
    #For now lets just add this list onto our str_num_list 
    #without worrying about converting to int. 
    #We use '+=' instead of 'append' since both stuff and str_num_lst are lists 
    str_num_lst += stuff 

#Print out the str_num_list to check if everything's ok 
print str_num_lst 

#Get an overall sum by looping over the string numbers in the str_num_lst 
#Can convert to int inside the loop 
overall_sum = 0 
for str_num in str_num_lst: 
    overall_sum += int(str_num) 

#Print sum 
print 'Overall sum is:' 
print overall_sum 

EDIT:

あなたは一行が良い解決策であるとして、ファイル全体を読み込む、右であり、それは行うことは難しいことではありません。チェックアウト:this postコードは次のようになります。

import re 

hand = open('a.txt') 
all_lines = hand.read() #Reads in all lines as one long string 
all_str_nums_as_one_line = re.findall('[0-9]+',all_lines) 
hand.close() #<-- can close the file now since we've read it in 

#Go through all the matches to get a total 
tot = 0 
for str_num in all_str_nums_as_one_line: 
    tot += int(str_num) 

print 'Overall sum is:',tot 
+0

ありがとうございました。私はlen(もの)ならば私が間違っていたことを知っていた...ライン。私はそれを理解することができませんでした。 '+ ='は正しいオプションです。それを共有してくれてありがとう。そしてエントリーレベルのプログラマーとして、ファイル全体を単一の文字列として読み込み、その文字列から '[0-9] +'を使用して抽出することができるかどうか疑問に思っていますか? –

+0

はい、良い点!私はそのオプションを含めるように私の答えを編集しました – mitoRibo

+0

それは素晴らしいです。どうもありがとうございます。 –

関連する問題