2016-09-14 75 views
1

我是新來的python,我不知道如何讓這個程序忽略標點符號;我知道這真的是效率低下,但我現在還沒有爲此感到困擾。我怎樣才能讓這個程序忽略標點符號

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 

我感謝所有幫助您可以給我

+0

你只是想剝離一切不是:a-zA-Z0-9還是你有一個標點符號來測試? – Fallenreaper

回答

1

您可以使用Python的string模塊,以幫助測試標點符號。

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

您可以在每個空間split句子從你的句子拿到個人的話,那麼從每個字去掉標點符號。或者,您可以先從句子中刪除標點符號,然後重新組成單個單詞。我們將做選項2 - 製作句子中所有字符的列表(標點符號除外),然後將該列表加入到一起。

>> 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' 

請注意,「未」的撇號被刪除 - 完全忽略標點符號的副作用。

相關問題