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
「a.txt」の行のいくつかを表示できますか? – mitoRibo
お返事ありがとうございます。下のリンクは、ファイル内のテキスト全体にリダイレクトされます。 http://python-data.dr-chuck.net/regex_sum_325354.txt –