2017-05-01 62 views
0

我的英語和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

你想檢查每個逗號分隔的單詞是否是迴文?我的意思是閱讀文件,並檢查plaindormity的單詞,安娜,keek,便便等。 – marmeladze

+0

感謝您的回答! ,不,我不會檢查逗號..我必須嘗試在循環中使用拆分(),蝙蝠我不知道怎麼做..... – d68745

+0

我必須寫:爲我在f.split(「 ,「):和我來,AttributeError:'文件'對象沒有'拆分'的屬性 – d68745

回答

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 
+0

感謝您的工作,但在我的閒置控制檯我來:安娜keek嘟嘟船尾eguzki 非迴文 – d68745

+0

sorryyyyyyy,我從我的文字損失的字符串,....我回答你的直覺! 「安娜」迴文 「keek」迴文 「嘟嘟」迴文 「便便」迴文 「eguzki」 不是迴文 – d68745

+0

首先非常感謝您的回答和你的工作! ,我有一個問題....怎麼辦[0] – d68745

相關問題