0

I'm a beginning programmer and I've been having some trouble with my assignment. So i'm hoping you will be able to help me with it. My assignment is as follows:

Write a program in Python that displays on the screen the last 3 words of lines read from a text file entered as standard input. Assume that all lines in the text file contain at least three words. Consider as a word only a string of at least one letter.

This is the input text file:

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.

and this should be the output:

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

However, it seems I'm required to remove all punctuation as well. And this is what i'm having trouble with. So here's my code:

import sys

def main():

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

main()
trent
  • 25,033
  • 7
  • 51
  • 90
Raisin
  • 1
  • 1
  • What have you tried to remove punctuation? – Evan Oct 06 '17 at 18:06
  • 2
    Possible duplicate of [Best way to strip punctuation from a string in Python](https://stackoverflow.com/questions/265960/best-way-to-strip-punctuation-from-a-string-in-python) – Jeremy McGibbon Oct 06 '17 at 18:06

1 Answers1

0

The best way to do this is s.translate(None, string.punctuation)

liam
  • 1,918
  • 3
  • 22
  • 28
  • If you need an alternative I would be happy to provide one but none will beat what I have put in terms of efficiency – liam Oct 06 '17 at 18:09