Вот моя программа до сих пор. Когда я запускаю его, я получаю сообщение об ошибке: «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()
Что такое ошибка, возникающая при объявлении ее как глобальной? –