很好,謝謝你包括整個txt文件!你的主要問題是if len(stuff)...
這條線跳過,如果stuff
沒有東西和它有2,3等等。您只保留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 –