从一个递归文件中选取单词,并在另一个文件python中打印出来

2024-04-26 03:20:06 发布

您现在位置:Python中文网/ 问答频道 /正文

从文件中获取输入(字符串测试.txt)只输出 回文到另一个文件tringsArePalindromes.txt文件). 忽略空格、大小写和标点符号

确定字符串是否为回文时,如果是回文,则将原始字符串写入文件

到目前为止,我已经做到了:

def ispalindrome(text):
    file=open(str(text),"r")
    a=file.readlines()
    #f=open(str("stringsarepalindromes.txt"),"w")
    for x in a:
        nomorepunc=x.replace("!","")
        nopunc=nomorepunc.replace(".","")
        nospace=nopunc.replace(" ","")
        samecase=(nospace.lower())
        morecase=samecase.replace("?","")
        evencase=morecase.replace("'","")
        cases=evencase.replace(":","")
        #print(cases)
        words=str(cases)
        c=words.split()


        if len(c) < 2:

            print(c,"true")
            #f.write(y)

        if c[0]!= c[-1]:
            print("no")



        return ispalindrome(c[1:-1])
    #open("stringsarepalindromes.txt")"""

Tags: 文件字符串texttxtopenreplacefileprint
2条回答

这将删除所有标点符号并将回文写入新文件:

import string
def ispalindrome(text):
    with open(text) as f,open("output.txt","w") as f1: # use with to open your files to close them automatically
        for line in f:
            test = line.strip().lower().translate(string.maketrans("",""), string.punctuation).replace(" ","") # remove punctuation and whitespace
            if test[::-1] == test: # if the line and line reversed are equal, we have a palindrome
                f1.write(line) # write original line to outfile.txt
            print "Is {} a palindrome? {}".format(test,test[::-1] == test) # just a line to show you what is happening

删除所有标点符号:

remove = "!.?':,"   # put all characters you want to remove in here

要去掉这些字符,并降低字符串中的所有字母,您可以说(其中x是您的字符串)

x = "".join([i.lower() for i in x if i not in remove])

之后,您可以通过简单地检查反向字符串来测试回文。你知道吗

x == x[::-1]

相关问题 更多 >