2015-06-24 2 views
0

Вот моя программа до сих пор. Когда я запускаю его, я получаю сообщение об ошибке: «UnboundLocalError: локальная переменная« txt », на которую ссылаются перед назначением». Я попытался добавить global перед txt, чтобы объявить его глобальной переменной, но я получаю еще одну ошибку, когда я это делаю. Любые идеи, что я делаю неправильно? Заранее спасибо.UnboundLocalError: локальная переменная 'txt', на которую ссылаются до назначения

def getwords(): 
    #function to get words in the input file 
    try: 
     global txt 
     txt=open("sample.txt",'r') 
    except IOError: 
     print('Unable to open file') 

    words=[] 

    #read the file line by line 
    for line in txt: 
     #convert each line into words with space as delimiter 
     words=words+line.split() 

    return words 

def wordcount(wordlist): 
    #function to count words in the file 
    #worddic is dictionary to store words frequency 
    worddic=dict() 

    for x in wordlist: 
     #convert word to lowercase to ignorecase 
     t=x.lower() 
     if(t not in worddic): 
      worddic[t]=0 

     worddic[t]=worddic[t]+1 

    max=-1 
    t='' 

    for x in worddic: 
     if(worddic[x]>max): 
      max=worddic[x] 
      t=x 

    return t 

def letters(wordlist,lettercount): 
    #function to count letters in the file 
    for x in wordlist: 
     #For each word in the list 
     t=x.lower() 

     for y in t: 
      #for each letter in the word 
      if(not (y in lettercount)): 
       #if the letter is not in dictionary add it 
       #and set frequency to zero 
       lettercount[y]=0 

      #increment the frequency of letter in dictionary 
      lettercount[y] = lettercount[y]+1 

def createoutput(lettercount,wordlist,mostword): 
    #creates an empty file 'statistics.txt' 
    try: 
     txt2=open("statistics.txt",'w+') 
    except IOError: 
     print('Unable to create file') 

    txt2.write('Number of words in the file are '+str(len(wordlist))+'\n') 
    txt2.write('Most repeated word in the file is '+mostword+'\n') 

    for x in lettercount: 
     #write to the file 'statistics.txt' 
     txt2.write(x+' appeared in the file for '+str(lettercount[x])+' times \n') 

def main(): 
    wordlist=getwords() 

    #lettercount is a dictionary with letters as keys 
    #and their frequency in the input file as data 

    lettercount=dict() 
    mostword=wordcount(wordlist) 
    letters(wordlist,lettercount) 
    createoutput(lettercount,wordlist,mostword) 

main() 
+0

Что такое ошибка, возникающая при объявлении ее как глобальной? –

ответ

0

При сбое open() вызова, вы проглотите исключение:

try: 
    global txt 
    txt=open("sample.txt",'r') 
except IOError: 
    print('Unable to open file') 

Теперь txt не никогда назначенную, потому что это open() вызова, который терпит неудачу здесь. Вместо того, чтобы продолжать функции, вы должны вернуться в этот момент:

try: 
    txt=open("sample.txt",'r') 
except IOError: 
    print('Unable to open file') 
    return 
+0

Спасибо! Это очень помогло. –

0

Вы хотите структурировать исключения, как это:

try: 
    # normal code here 
except: 
    # handle the exception 

Например, этот код является неправильным, поскольку он запускает код, который может не в состоянии вне обработчика исключений

def createoutput(lettercount,wordlist,mostword): 
    #creates an empty file 'statistics.txt' 
    try: 
     txt2=open("statistics.txt",'w+') 
    except IOError: 
     print('Unable to create file') 

    txt2.write('Number of words in the file are '+str(len(wordlist))+'\n') 
    txt2.write('Most repeated word in the file is '+mostword+'\n') 

Moving нормального чтения в обработчик исключений будет выглядеть следующим образом

def createoutput(lettercount,wordlist,mostword): 
    #creates an empty file 'statistics.txt' 
    try: 
     txt2=open("statistics.txt",'w+') 
     txt2.write('Number of words in the file are '+str(len(wordlist))+'\n') 
     txt2.write('Most repeated word in the file is '+mostword+'\n') 
    except IOError: 
     print('Unable to create file') 

но вы никогда не закрывали файл. Где вы помещаете команду close file? После того, как вы открыли его, очевидно, но что произойдет, если txt2.write выдает исключение? Что делать, если какая-то другая проблема происходит там? Ты никогда не закрываешься!

С файлами вы хотите сделать это, так что файл закрывается, когда он выходит из сферы

with open("statistics.txt", "w+") as statsfile: 
    statsfile.write("Number of words ... 

и, конечно же, вы положили, что в качестве обработчика исключений

def getwords(filename="sample.txt"): 
    words = [] 
    try: 
     with open (filename, 'r') as txt: 
      for line in txt: 
       words = words + line.split() 
    except IOError: 
     print "unable to open file" 
    return words