2017-10-06 263 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

如果你需要替代方案,我会很乐意提供一个,但没有一个会在效率方面超过我所提出的 –

相关问题