回文|帕帕尔·恩·德罗姆| noun 向后读与向前读相同的单词、短语或序列,例如,女士或护士跑.

"palindrome_finder"项目包括3个文件:名为"dict.yx"的词典文件、名为"feed_dictionary. py"的词典加载器文件,以及名为"palingram_finder. py"的主文件(识别词典文件中的palindrome).

一旦我运行该文件,我就会收到以下错误:

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]

对于上下文,这里是两个pony文件.

100

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("{}\n Error opening {}. Terminating program.".format(e, file), file=sys.stderr)
        sys.exit(1)

100

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: {}\n\n".format(len(palindrome_list)))
pp(palindrome_list)

Attempts at a fix: 我使用内置的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()

由于它有效,我认为问题出在加载字典的方式上. 这就是我陷入困境的地方,因为当我以与load_dictionary.py相同的方式在Sublime text editor's shell中加载字典时,我会得到一个字符串列表.那么它不应该起作用吗?

推荐答案

您收到的错误是由于load_dictionary.py文件中的这一行造成的:

loaded_txt = [x.lower for x in loaded_txt]

您不是调用x.lower,只是引用它.将其称为方法:

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

这将解决您的问题.😊

Python相关问答推荐

在使用Guouti包的Python中运行MPP模型时内存不足

用gekko解决的ADE方程系统突然不再工作,错误消息异常:@错误:模型文件未找到.& &

比较两个二元组列表,NP.isin

numba jitClass,记录类型为字符串

如何使用matplotlib在Python中使用规范化数据和原始t测试值创建组合热图?

未删除映射表的行

海运图:调整行和列标签

通过Selenium从页面获取所有H2元素

将图像拖到另一个图像

对象的`__call__`方法的setattr在Python中不起作用'

使用密钥字典重新配置嵌套字典密钥名

字符串合并语法在哪里记录

Django—cte给出:QuerySet对象没有属性with_cte''''

重置PD帧中的值

具有相同图例 colored颜色 和标签的堆叠子图

如何按row_id/row_number过滤数据帧

Pandas—MultiIndex Resample—我不想丢失其他索引的信息´

我怎么才能用拉夫分拣呢?

BeatuifulSoup从欧洲志愿者服务中获取数据和解析:一个从EU-Site收集机会的小铲子

在任何要保留的字段中添加引号的文件,就像在Pandas 中一样