2013-01-24 3 views
0

파일 이름을 묻는 프로그램을 작성한 후 파일을 읽고 양식 줄을 찾으십시오. X-DSPAM-Confidence : 0.8475 "X-DSPAM-Confidence : "행을 분리하여 행의 부동 소수점 수를 추출합니다. 이 라인을 세어 이들 라인에서 스팸 신뢰도 값의 합계를 계산하십시오. 파일의 끝에 도달하면 평균 스팸 신뢰도를 인쇄하십시오.파이썬은 for 루프를 사용하여 라인을 파싱합니까?

파일 이름을 입력 : 0.894128046745

파일 이름 입력 :
평균 스팸 지수 mbox.txt MBOX-short.txt을
평균 스팸 지수 다음 mbox.txt에 0.750718518519 테스트 파일 및 mbox-short.txt 파일.

지금까지 내가 가진 :

fname = raw_input("Enter file name: ") 
fh = open(fname) 
for line in fh: 
    pos = fh.find(':0.750718518519') 
    x = float(fh[pos:]) 
    print x 

이 코드에 문제가 있습니까? 당신이

print pos #prints 디버깅에 도움이 줄을 .... 검색 할 수 있도록

답변

4

그들은 0.750718518519이 아니라 'X-DSPAM-Confidence'의 평균을 구하는 것 같습니다.

저는 개인적으로 찾고있는 단어를 찾고 번호를 추출한 다음 모든 숫자를 목록에 넣고 끝에 평균을 구합니다. 우리는 find()는 단지 우리에게 각 라인에서 'X-DSPAM-Confidence:'의 위치가 아닌 위치를주는 것을 볼 수 있습니다

>>> for line in lines.splitlines(): 
    pos = line.find('X-DSPAM-Confidence:') 
    print pos 

0 
0 
-1 
0 

: -이 같은

뭔가

# Get the filename from the user 
filename = raw_input("Enter file name: ") 

# An empty list to contain all our floats 
spamflts = [] 

# Open the file to read ('r'), and loop through each line 
for line in open(filename, 'r'): 

    # If the line starts with the text we want (with all whitespace stripped) 
    if line.strip().startswith('X-DSPAM-Confidence'): 

     # Then extract the number from the second half of the line 
     # "text:number".split(':') will give you ['text', 'number'] 
     # So you use [1] to get the second half 
     # Then we use .strip() to remove whitespace, and convert to a float 
     flt = float(line.split(':')[1].strip()) 

     print flt 

     # We then add the number to our list 
     spamflts.append(flt) 

print spamflts 
# At the end of the loop, we work out the average - the sum divided by the length 
average = sum(spamflts)/len(spamflts) 

print average 

>>> lines = """X-DSPAM-Confidence: 1 
X-DSPAM-Confidence: 5 
Nothing on this line 
X-DSPAM-Confidence: 4""" 

>>> for line in lines.splitlines(): 
    print line 


X-DSPAM-Confidence: 1 
X-DSPAM-Confidence: 5 
Nothing on this line 
X-DSPAM-Confidence: 4 

는 찾기를 사용하여 그 이후의 숫자의

이 라인이 'X-DSPAM-Confidence:'로 시작하면이 같은 단지 수를 추출 후,보다 쉽게 ​​찾을 수 : 여전히 P (+1을을주는 : 당신은 그냥 실제로 그를 위해 자신의 임무를했다 ㅎ

>>> for line in lines.splitlines(): 
    print line.startswith('X-DSPAM-Confidence') 


True 
True 
False 
True 

>>> for line in lines.splitlines(): 
    if line.startswith('X-DSPAM-Confidence'): 
     print line.split(':') 


['X-DSPAM-Confidence', ' 1'] 
['X-DSPAM-Confidence', ' 5'] 
['X-DSPAM-Confidence', ' 4'] 

>>> for line in lines.splitlines(): 
    if line.startswith('X-DSPAM-Confidence'): 
     print float(line.split(':')[1]) 


1.0 
5.0 
4.0 
+0

정답) –

+0

@JoranBeasley 네, 그렇게 생각합니다. 그것은 아마도 배울 수있는 최선의 방법은 아니지만 잘하면 그가 그것을 읽고 시도하고 이해하게 될 것입니다. (더 숙제 태그가 없나요?) –

+0

@JoranBeasley 나는 그를 이해하는 데 도움이되는 몇 가지 코멘트를 추가했습니다. –

-1

line.find # .....)

float(fh[pos+1:]) 당신이있어 #the 인덱스가 실제로 인 : 그래서 당신은 필요 1 이상으로 이동

0
fname = raw_input("Enter file name: ") 
with open(fname) as f: 
    spam = [float(line.split(':', 1)[1]) for line in f if line.startswith('X-DSPAM-Confidence: ')] 
count = len(spam) 
avg = sum(spam)/len(spam) 
관련 문제