2017-10-06 13 views
0

私は初心者です。私は自分の課題に悩まされています。だから私はあなたがそれを手伝ってくれることを願っています。私の割り当ては次のとおりです:Python 3がテキストファイルからパンクチュエーションを削除する

標準入力として入力されたテキストファイルから読み込まれた行の最後の3単語を画面に表示するPythonでプログラムを記述します。テキストファイルのすべての行に少なくとも3つの単語が含まれているとします。少なくとも1文字の文字列だけを単語として考えてください。

これは、入力テキストファイルです:

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

あなたが代替品を必要とするなら、私は1つを提供してもうれしいですが、どれも効率の面では何もないでしょう –

関連する問題