2017-10-06 266 views
0

我是一個開始的程序員,我一直在爲我的任務遇到一些麻煩。所以我希望你能幫助我。我的任務如下:Python 3從文本文件中刪除標點符號

用Python編寫一個程序,該程序在屏幕上顯示從作爲標準輸入輸入的文本文件中讀取的行的最後3個字。假設文本文件中的所有行至少包含三個單詞。考慮一個字只有至少一個字母的字符串。

這是輸入文本文件:

Elizabeth it is in vain you say 
"Love not"â€」thou sayest it in so sweet a way: 
In vain those words from thee or L.E.L. 
Zantippe's talents had enforced so well: 
Ah! if that language from thy heart arise, 
Breath it less gently forthâ€」and veil thine eyes. 
Endymion, recollect, when Luna tried 
To cure his loveâ€」was cured of all besideâ€」 
His follieâ€」prideâ€」and passionâ€」for he died. 

,這應該是輸出:

vain you say 
sweet a way 
l e l 
enforced so well 
thy heart arise 
veil thine eyes 
when luna tried 
of all beside 
for he died 

但是,似乎我需要刪除所有標點爲好。這就是我遇到的麻煩。因此,這裏是我的代碼:

import sys 

def main(): 

    for item in sys.stdin: 
     item = item.split()[-3:] 
     string = ' '.join(item) 
     print (string) 

main() 
+0

你嘗試過什麼刪除標點? – Evan

+2

[在Python中刪除標點符號的最佳方法]可能的副本(https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python) –

回答

0

做到這一點,最好的辦法是s.translate(None, string.punctuation)

+0

如果你需要替代方案,我會很樂意提供一個,但沒有一個會在效率方面超過我所提出的 –

相關問題