Python:获取了一条错误语句;局部变量';idx';作业前参考“; def removeNonAlpha(myString,key): 从字符串导入ascii_小写 字母表=ascii_小写字母+“” myString=myString.lower() 密文=“” 对于ch in myString: 如果ch==1或ch==2或ch==3或ch==4或ch==5或ch==6或ch==7或ch==8或ch==9: idx=字母表查找(ch) 密文=密文+密钥[idx] 返回密文

Python:获取了一条错误语句;局部变量';idx';作业前参考“; def removeNonAlpha(myString,key): 从字符串导入ascii_小写 字母表=ascii_小写字母+“” myString=myString.lower() 密文=“” 对于ch in myString: 如果ch==1或ch==2或ch==3或ch==4或ch==5或ch==6或ch==7或ch==8或ch==9: idx=字母表查找(ch) 密文=密文+密钥[idx] 返回密文,python,Python,使用以下命令运行我的脚本: removeNonAlpha('我最喜欢的猫叫Patches',字母表) 返回以下错误 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 =

使用以下命令运行我的脚本:

removeNonAlpha('我最喜欢的猫叫Patches',字母表)
返回以下错误

          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):
从字符串导入ascii_小写
字母表=ascii_小写字母+“”
myString=myString.lower()
密文=“”
对于ch in myString:
idx=#设置一些默认值
如果ch in['123456789']:
idx=字母表查找(ch)
密文=密文+密钥[idx]
返回密文

您必须使用一些默认值初始化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)`

想想当您的
条件在第一次迭代中为false时会发生什么,然后您不给
idx分配任何内容。另外,如果
myString
str
,那么
ch
将永远不会等于
int
,因为您正在条件中进行测试,请参见