回文|帕帕尔·恩·德罗姆| 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中加载字典时,我会得到一个字符串列表.那么它不应该起作用吗?