简体   繁体   English

在文件中搜索回文,并使用python将其打印在列表中

[英]Searching a file for palindromes and printing them in a list with python

Im trying to write a code that reads a file and then returns a list of all the palindromes in the file. 我试图编写代码来读取文件,然后返回文件中所有回文列表。 So I've created a function checks if a word is a palindrome and I've tried to write another function that reads the file, gets rid of the blank space, splits into words, and then tests each word to see if it is a palindrome. 因此,我创建了一个函数来检查一个单词是否是回文,并且我尝试编写另一个函数来读取文件,摆脱空格,拆分成单词,然后测试每个单词以查看它是否是一个回文。回文。 If it is a palindrome, then I add it into the list that I will print in the end. 如果是回文,则将其添加到最后要打印的列表中。 However, I am getting an error "AttributeError: 'tuple' object has no attribute 'append'" How can I get the palindromes added into this list? 但是,我收到一个错误“ AttributeError:'tuple'对象没有属性'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

The problem here is that list3 isn't actually a list. 这里的问题是list3实际上不是列表。 Instead of doing list3 = () , do list3 = [] . 而不是执行list3 = () ,而是执行list3 = []

Doing () will create a tuple , which is a type of data structure similar to a list, but cannot be altered after they're first created. Doing ()将创建一个tuple ,它是一种类似于列表的数据结构,但是在首次创建后就不能更改。 This is why you're unable to append to it, since that would alter the tuple. 这就是为什么您无法附加到它的原因,因为那样会改变元组。 The [] creates an actual list, which is mutable and can be altered over time. []创建一个实际的列表,该列表是可变的,可以随时间更改。

Remove: 去掉:

list3=() # because it creates an empty tuple

by: 通过:

list3=list() # create an empty list

Also replace : 同时替换:

list2 = line.split()

by: 通过:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM