用Python查找文件中的回文并以列表形式打印

1 投票
2 回答
790 浏览
提问于 2025-04-30 21:36

我正在尝试写一段代码,目的是读取一个文件,然后返回文件中所有的回文词。为此,我创建了一个函数,用来检查一个单词是否是回文词。接着,我又写了另一个函数,这个函数负责读取文件,去掉空白,分割成单词,然后测试每个单词是否是回文词。如果是回文词,我就把它加到最后要打印的列表里。不过,我遇到了一个错误:“AttributeError: 'tuple' object has no attribute 'append'”。我该怎么才能把回文词加到这个列表里呢?

def findPalindrome(filename):
    #an empty list to put palindromes into
    list3 = ()
    #open the file 
    for line in open(filename):
        #strip the lines of blank space
        list1 = line.strip()
        #Split the lines into words
        list2 = line.split()
        #call one of the words
        for x in list2:
            #test if it is a palindrome
            if isPalindrome(x):
                #add to list3
                list3.append(x)
    #return the list of palindromes
    return list3
暂无标签

2 个回答

1

这里的问题是,list3 实际上并不是一个列表。你应该用 list3 = [] 来创建它,而不是 list3 = ()

使用 () 会创建一个元组,这是一种类似于列表的数据结构,但一旦创建后就不能更改。这就是为什么你不能往里面添加东西,因为那样会改变元组的内容。而 [] 则会创建一个真正的列表,它是可变的,可以随时进行修改。

1

删除:

list3=() # because it creates an empty tuple

替换为:

list3=list() # create an empty list

同时替换:

list2 = line.split()

为:

list2 = list1.split() # because stripped line is in list1 not in line

撰写回答