有时,我们可能希望将一个句子分解成一个单词列表。
在这种情况下,我们可能首先需要清理字符串并删除所有标点符号。下面是一个如何完成此操作的示例。
源代码
# define punctuation
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
my_str = "Hello!!!, he said ---and went."
# To take input from the user
# my_str = input("Enter a string: ")
# remove punctuation from the string
no_punct = ""
for char in my_str:
if char not in punctuations:
no_punct = no_punct + char
# display the unpunctuated string
print(no_punct)
输出
Hello he said and went
在这个程序中,我们首先定义一个标点符号字符串。然后,我们使用 for
循环遍历所提供的字符串。
在每次迭代中,我们使用成员资格测试来检查该字符是否为标点符号。我们有一个空字符串,如果字符不是标点符号,我们就将它添加(连接)到这个空字符串中。最后,我们显示清理后的字符串。
另请阅读