You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

回文查找器代码运行报错:TypeError问题排查求助

回文识别程序错误排查

palindrome | ˈpalənˌdrōm |
名词
指正读和反读都相同的单词、短语或序列,例如madam或nurses run。

项目背景

“palindrome_finder”项目包含3个文件:

  • 字典文件:dict.txt
  • 字典加载文件:load_dictionary.py
  • 回文识别主文件:palingram_finder.py

运行错误信息

运行主程序时出现以下错误:

Traceback (most recent call last):
  File "/Users/cheshirecat/Desktop/python_projects/palingram_finder/palingram_finder.py", line 16, in <module>
    if word[::-1] == word and len(word) >= 3:
       ~~~~^^^^^^
TypeError: 'builtin_function_or_method' object is not subscriptable
[Finished in 58ms with exit code 1]

代码文件内容

load_dictionary.py

import sys

def load(file):
    """Open a text file and return a list of lowercase strings"""

    try:
        with open(file) as in_file:
            loaded_txt = in_file.read().strip().split()
            loaded_txt = [x.lower for x in loaded_txt]

            return loaded_txt

    except IOError as e:
        print("{}
 Error opening {}. Terminating program.".format(e, file), file=sys.stderr)
        sys.exit(1)

palingram_finder.py

from load_dictionary import load
from pprint import pp

word_list = load('./dict.txt')
palindrome_list = []

for word in word_list:
    if word[::-1] == word and len(word) >= 3:
        palindrom_list.append(word)

print("Number of palindromes found: {}

".format(len(palindrome_list)))
pp(palindrome_list)

已尝试的修复操作

在Python内置shell测试简化版代码,运行正常:

>>> word_list = ['betrayal', 'enigma', 'tenet', 'multitude', 'did']
>>> 
>>> palindrome_list = []
>>> 
>>> for word in word_list:
...     if len(word) >= 3 and word[::-1] == word:
...             palindrome_list.append(word)
... 
>>> palindrome_list
['tenet', 'did']
>>> exit()

判断问题出在字典加载方式,但在Sublime Text编辑器shell中按相同方式加载字典得到的是字符串列表,主程序仍报错,求助解决。


问题解决

1. 核心错误点

load_dictionary.py中loaded_txt = [x.lower for x in loaded_txt]这一行,x.lower是引用字符串的lower方法对象,而非调用该方法生成小写字符串。因此word_list中的每个元素都是方法对象,不是字符串,导致word[::-1]触发下标访问错误。

2. 修复代码

修改load_dictionary.py中的对应行:

loaded_txt = [x.lower() for x in loaded_txt]

添加括号调用lower()方法,将每个字符串转为小写形式。

3. 额外拼写错误修正

palingram_finder.py中存在拼写错误:palindrom_list.append(word)应改为palindrome_list.append(word)(少写了一个字母'e'),否则会触发NameError异常。


内容的提问来源于stack exchange,提问作者FatTony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 03:57:51