[英]Python - If statement, error local variable 'newfile' referenced before assignment
[英]Python: Got an Error Statement for "local variable 'idx' referenced before assignment"
def removeNonAlpha(myString, key):
from string import ascii_lowercase
alphabet = ascii_lowercase + ' '
myString = myString.lower()
cipherText = ' '
for ch in myString:
if ch == 1 or ch == 2 or ch == 3 or ch == 4 or ch == 5 or ch == 6 or ch == 7 or ch == 8 or ch == 9 :
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
運行我的腳本:
removeNonAlpha('My favorite Cat was named Patches', alphabet)
返回以下錯誤
7 if ch == 1 or ch == 2 or ch == 3 or ch == 4 or ch == 5 or ch == 6 or ch == 7 or ch == 8 or ch == 9 :
8 idx = alphabet.find(idx)
----> 9 cipherText = cipherText + key[idx]
10 return cipherText
UnboundLocalError: local variable 'idx' referenced before assignment
我的代碼有什么問題?
這意味着您在創建之前嘗試使用變量“idx”。 'idx' 僅在 if 內部創建,但使用 'idx' 的行在 'if' 語句之外,因此即使在 'if' 失敗時它也會運行
只需將功能更改為以下內容:
def removeNonAlpha(myString, key):
from string import ascii_lowercase
alphabet = ascii_lowercase + ' '
myString = myString.lower()
cipherText = ' '
for ch in myString:
if ch == 1 or ch == 2 or ch == 3 or ch == 4 or ch == 5 or ch == 6 or ch == 7 or ch == 8 or ch == 9 :
idx = alphabet.find(ch)
cipherText = cipherText + key[idx] #edits
return cipherText
這是因為如果條件未通過,則您的 idx 未初始化,此外,您可以對大量條件進行一些更改,請嘗試以下操作:
def removeNonAlpha(myString, key):
from string import ascii_lowercase
alphabet = ascii_lowercase + ' '
myString = myString.lower()
cipherText = ' '
for ch in myString:
idx = #make some default value
if ch in ['123456789']:
idx = alphabet.find(ch)
cipherText = cipherText + key[idx]
return cipherText
您必須使用一些默認值初始化 idx 並且可以添加檢查是否找到 idx 。
更新:完全改變了我的代碼,但這是工作結果:
`def removeNonAlpha(myString):
from string import ascii_lowercase
alphabet = ascii_lowercase + ' '
myString = myString.lower()
cipherText = ' '
return myString
def getFreq(tuples):
return tuples[1]
# this returns the second element of a tuple #
countDict = {}
with open('wells.txt', 'r', encoding='utf-8') as wells:
text = wells.read()
for word in text.split():
word = removeNonAlpha(word)
if word in countDict:
countDict[word] += 1
else:
countDict[word] = 1
wordList = list(countDict.items())
wordList.sort(key = getFreq)
for wordTuple in wordList[-10:]:
print(wordTuple)`
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.