gpt4 book ai didi

python - 我怎样才能让这个程序忽略标点符号

转载 作者:太空宇宙 更新时间:2023-11-03 16:08:41 25 4
gpt4 key购买 nike

我是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

感谢您能给我的任何帮助

最佳答案

您可以使用 Python 的 string 模块来帮助测试标点符号。

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

您可以在每个空格处拆分句子,以从句子中获取各个单词,然后从每个单词中删除标点符号。或者,您可以先从句子中删除标点符号,然后重新组成各个单词。我们将执行选项 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'

请注意,“haven't”中的撇号已被删除 - 这是完全忽略标点符号的副作用。

关于python - 我怎样才能让这个程序忽略标点符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39496745/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com