python中使用文件i/o的回文程序



我是python的新手,正在编写一些程序来掌握它。我正在制作一个回文程序,它从文件中获取输入并打印出回文单词。这是我到目前为止的代码

def isPalindrome(word):
    if len(word) < 1:
        return True
    else:
        if word[0] == word[-1]:
            return isPalindrome(word[1:-1])
        else:
            return False
def fileInput(filename):
    file = open(filename,'r')
    fileContent = file.readlines()
    if(isPalindrome(fileContent)):
        print(fileContent)
    else:
        print("No palindromes found")
    file.close()

这是文件

moom
mam
madam
dog
cat
bat

我没有找到回文的输出。

文件的内容将以列表的形式读取,因此fileContent最终将显示为:

fileContent = file.readlines()
fileContent => ["moonn", "mamn", "madamn", "dogn", "catn", "batn"]

你可以通过以下方式解决这个问题:

def fileInput(filename):
    palindromes = False
    for line in open(filename):
        if isPalindrome(line.strip()):
             palindromes = True
             print(line.strip(), " is a palindrome.")
    return "palindromes found in {}".format(filename) if palindromes else "no palindromes found."

注意:添加了palindromes标志,用于返回最终的"未找到回文"语句

文件中的单词应该有一个循环。此外,readline也读取行尾字符。在调用isPalindome之前,您应该先strip它。

使用

fileContent = file.readline().strip()

因为readlines()返回具有'n'字符的字符串的列表。

此外,readlines()返回列表,其中readline()返回当前行。

也不要使用file作为变量名。

所以你修改的fileInput():

def fileInput(filename):
    f = open(filename,'r')
    line = f.readline().strip()
    while line != '':
        if(isPalindrome(line)):
            print(line)
        else:
            print("No palindromes found")
        line = f.readline().strip()
    file.close()

最新更新