从文件(stringsToTest.txt)获取输入并仅输出字符串 回到另一个文件(stringsArePalindromes.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")"""
答案 0 :(得分:1)
删除所有标点符号:
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]
答案 1 :(得分:0)
这将删除所有标点符号并将回文标记写入新文件:
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