전체 txt 파일을 포함 해 주셔서 감사합니다. 귀하의 주된 문제는 stuff
에 0 점이 있고 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
편집 :
당신은 한 줄 좋은 솔루션으로 전체 파일에 읽기, 맞다, 그것은 할 어렵지 않다. 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 –