繁体   English   中英

Python:得到了“分配前引用的局部变量‘idx’”的错误语句

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM