我的英语和Python知识非常低..... 所以,我的问题,写一个从用户接受文件名的回文识别器的版本,读取每一行,如果它是回文,则将该行打印到屏幕上。
我的代码:
that is was i write to the textfile: "anna" "keek" "toot" "poop" "eguzki"
def palindrome():
with open('home/me/pytho/textfile.txt', 'r') as f:
for i in f:
if i == i[:-1]:
new = i
print new
palindrome()
但我什么都没有...请用简单的单词回答,因为我的代码不是直觉,谢谢!
答案 0 :(得分:1)
示例文本文件
$ cat ex.txt
"anna", "keek", "toot", "poop", "eguzki"
python代码
def is_palindrome(word):
return word == word[::-1]
with open('ex.txt') as f:
words = f.readlines()[0].split(", ")
for word in words:
print word, "palindrome" if is_palindrome(word) else "not palindrome"
执行代码。
$ python palindrome.py
"anna" palindrome
"keek" palindrome
"toot" palindrome
"poop" palindrome
"eguzki" not palindrome