Großartig, danke für die Aufnahme der ganzen TXT-Datei! Ihr Hauptproblem war in der if len(stuff)...
Zeile, die übersprungen wurde, wenn stuff
null Dinge drin hatte und wenn es 2,3 und so weiter hatte. Sie haben nur stuff
Listen der Länge 1 behalten. Ich habe Kommentare in den Code geschrieben, aber bitte stellen Sie Fragen, wenn etwas unklar ist.
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:
Sie haben Recht, in der gesamten Datei zu lesen als eine Zeile ist eine gute Lösung, und es ist nicht schwer zu tun. Schauen Sie sich this post an. Hier ist, wie der Code aussehen könnte.
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
Können Sie zeigen, wie einige der Zeilen in "a.txt" aussehen? – mitoRibo
Danke für die Antwort. Der folgende Link leitet den gesamten Text in der Datei um. http://python-data.dr-chuck.net/regex_sum_325354.txt –