2015-04-21 237 views
0

所以我有這個Python代碼我正在打開一個文件,並從中讀取最大和最小分數百分比,然後顯示最大分數的團隊以及具有分得分是0.75和0.125 我不斷收到此錯誤信息:Python從文件中讀取

ValueError: invalid literal for int() with base 10: '0.75' 

我會很感激的任何幫助,請和謝謝。

這是我與http://www.filedropper.com/nfldata

工作文件下面是我的代碼:

def create_score_list(nfl_file): 
    """Create a list of teams and scores from nfl_file.""" 
    # 2a create a score list and initialize it to empty 
    score_list = [] 

for line in nfl_file:    # 2b. get each line from the file 
    if line[0:28] == 'National Football Conference' or\ 
      'NFC EAST' in line or\ 
      'NFC NORTH' in line or\ 
      'NFC SOUTH' in line or\ 
      'NFC WEST' in line or\ 
      'AFC EAST' in line or\ 
      'AFC NORTH' in line or\ 
      'AFC SOUTH' in line or\ 
      'AFC WEST' in line: 
     continue     # skip header line 
    line_list = line.split(',')   # 2bI. csv => split on comma 
    # create tuple: 
    team_tuple = (int(line_list[4]), line_list[0]) 
    score_list.append(team_tuple)  # 2bII. append tuple 
return score_list 

回答

0

這是因爲有時line_list[4]float,有時是string。但是你總是將它解析爲int。另外,你需要先篩選CSV值跳過頭,你現在正在做這樣的:

if line[0:28] == 'National Football Conference' or\ 
     'American Football Conference' in line or\ 
     'NFC EAST' in line or\ 
     'NFC NORTH' in line or\ 
     'NFC SOUTH' in line or\ 
     'NFC WEST' in line or\ 
     'AFC EAST' in line or\ 
     'AFC NORTH' in line or\ 
     'AFC SOUTH' in line or\ 
     'AFC WEST' in line: 

但你缺少某些情況下。您可以通過檢查line_list[4]中的值是否爲float來簡化它。

try: 
    score = float(line_list[4]) 
except ValueError: 
    continue # The value isn't a float 

所以create_score_list(nfl_file)是:

def create_score_list(nfl_file): 
    """Create a list of teams and scores from nfl_file.""" 
    # 2a create a score list and initialize it to empty 
    score_list = [] 

    for line in nfl_file:    # 2b. get each line from the file 
     line_list = line.split(',')   # 2bI. csv => split on comma 
     score = None 
     try: 
      score = float(line_list[4]) 
     except ValueError: 
      continue # The value isn't a float 

     # create tuple: 
     team_tuple = (score, line_list[0]) 
     score_list.append(team_tuple)  # 2bII. append tuple 
    return score_list 
+0

耶字符串問題是我面臨什麼,但我得到了什麼你沒有感謝您的幫助真的很感激! – Manny

+0

我很高興這爲你工作。如果此答案對您有幫助,請點擊複選標記,考慮[接受](http://meta.stackexchange.com/q/5234/179419)。 :) –