2016-10-18 5 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에 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 
+0

정말 고마워요. 내가 len (물건)이라면 내가 잘못하고 있었다는 것을 알았어. 나는 그것을 aproach 알아낼 수 없었다. '+ ='는 올바른 옵션입니다. 공유해 주셔서 감사합니다. 그리고 엔트리 레벨 프로그래머로서, 전체 파일을 단일 문자열로 읽고 문자열에서 '[0-9] +'를 사용할 수 있는지 궁금합니다. –

+0

예, 좋은 지적입니다! 해당 옵션을 포함하도록 내 대답을 편집했습니다 – mitoRibo

+0

그게 좋네요. 정말 고맙습니다. –

관련 문제