只是想比较一个项目,但得到UndefinedVariableError

问题描述 投票:-1回答:1

我正在编写一个简单的脚本,将输入消息转换为一系列十进制的ASCII码,并不断获得UndefinedVariableError,无法弄清它为什么会发生。这是我的代码:

def convert_text_dec():
    message_to_encode = input('Enter a message: ')
    glossary = pd.read_excel('ascii-table.xls', skiprows=[0,1],
                             usecols=['dex', 'symbol'], nrows=256)
    ascii_message = []    

    letters = list(message_to_encode)
    for item in letters:
        letter = glossary.query(f'symbol=={item}')['dex'].iloc[0]
        ascii_message.append(letter)

    print(ascii_message)

在同一文件中,我有一个完全相同的功能,其功能相反,但没有问题,但是当我尝试运行convert_text_dec并例如输入“ hello”作为消息时,出现以下错误:


  File "F:/python/binary_to_text/bin2text.py", line 52, in <module>
    convert_text_dec()

  File "F:/python/binary_to_text/bin2text.py", line 47, in convert_text_dec
    letter = glossary.query(f'symbol=={item}')['dex'].iloc[0]

...
...
UndefinedVariableError: name 'h' is not defined

我在这里做错了什么?

python pandas ascii
1个回答
1
投票

在您的代码中:

for item in letters:
    letter = glossary.query(f'symbol=={item}')['dex'].iloc[0]
    ascii_message.append(letter)

您正在为每个字母创建查询,例如。 symbol==h。 Pandas尝试评估查询,但未在任何地方定义变量h

{item}引用"应该可以解决问题:

letter = glossary.query(f'symbol=="{item}"')['dex'].iloc[0]
© www.soinside.com 2019 - 2024. All rights reserved.