我必须创建一个程序来测试输入字符串是否是回文。回文是与反向序列相同的单词序列,例如单词"noon"。计划要求如下:
- 您必须使用堆栈
- 程序应忽略字母以外的所有字符。
- 从文件输入
- 测试单个单词和完整句子
- 应该有一些真正的错误结果。
这是我到目前为止的代码:
f = open('myTextFile.txt', "r")
line = f.readline()
while line:
print(line)
line = f.readline()
exclude = set("-")
line = ''.join(ch for ch in line if ch not in exclude)
exclude = set(",")
line = ''.join(ch for ch in line if ch not in exclude)
exclude = set(".")
line = ''.join(ch for ch in line if ch not in exclude)
exclude = set(" ")
line = ''.join(ch for ch in line if ch not in exclude)
f.close()
我的问题是下一步该怎么做,我有点迷茫,我删除了所有多余的字符,我应该将每一行放入一个列表中以单独使用它们吗?你能引导我朝着正确的方向前进吗?
我不知道
这会对你有多大帮助,但要检查回文,我会做这样的事情:
# to get rid of spaces to check sentences (maybe repeat for punctuation marks)
line = line.replace(" ","")
# create reverse string see http://stackoverflow.com/questions/931092/reverse-a-string-in-python
reverse_line = line[::-1]
# check if it is a palindrome
print line == reverse_line
希望我能帮上一点忙