Motag8tor
Motag8tor

Reputation: 13

How can I make this program ignore punctuation

I'm new to python and I'm not sure how I can make this program ignore punctuation; I know it's really inefficient but I'm not bothered about it at this moment in time.

while True:
y="y"
n="n"

Sentence=input("Please enter your sentence: ").upper()
print("Your sentence is:",Sentence)
Correct=input("Is your sentence correct? y/n ")
if Correct==n:
    break
elif Correct==y:
    Location=0

    SplitSentence = Sentence.split(" ")
    for word in SplitSentence:
        locals()[word] = Location
        Location+=1
    print("")

    FindWord=input("What word would you like to search? ").upper()
    if FindWord not in SplitSentence:
        print("Your chosen word is not in your sentence")
    else:
        iterate=0
        WordBank=[]
        for word in SplitSentence:
            iterate=iterate+1
            if word == FindWord: 
                WordBank.append(iterate) 
        print(FindWord, WordBank) 

    break

I appreciate any help you can give me

Upvotes: 1

Views: 88

Answers (1)

souldeux
souldeux

Reputation: 3755

You can use Python's string module to help test for punctuation.

>> import string
>> print string.punctuation
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
>> sentence = "I am a sentence, and; I haven't been punctuated well.!"

You can split the sentence at each space to get the individual words from your sentence, then remove the punctuation from each word. Or, you can remove the punctuation from the sentence first then re-form the individual words. We'll do option 2 - make a list of all characters in the sentence, except for the punctuation marks, then join that list together.

>> cleaned_sentence = ''.join([c for c in sentence if c not in string.punctuation])
>> print cleaned_sentence
'I am a sentence and I havent been punctuated well'

Notice that the apostrophe from "haven't" got removed - a side effect of ignoring punctuation altogether.

Upvotes: 1

Related Questions