如何使用列表理解删除字符串中的标点符号?
How To Remove Punctuation In String Using List Comprehension?
如何使用列表理解删除字符串中的标点符号?
punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"
我知道如何使用 For 循环:
for i in text:
if i not in punctuations:
analyzed+=i
print(analyzed)
但是我如何使用列表理解来做到这一点?
punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"
试试这个:
>>[c for c in text if c not in punctuations]
您将获得:
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', ' ', ' ', ' ', 'A', ' ', 'S', 't', 'r', 'i', 'n', 'g', ' ']
如果你想把它作为一个字符串,只需将它们全部连接起来即可。
>>''.join(c for c in text if c not in punctuations)
'This is A String '
使用生成器,并将其作为参数传递给 join()
以将结果转换回字符串。
analyzed = ''.join(c for c in text if c not in punctuations)
print(analyzed)
你可以先把你的标点和字符串转换成一个列表,然后再分开,如下:
import string
list = ["!", "This","@", "#", "$", "is", "%", "a", "^", "&", "list", "*", "(", ")"]
list2 = [idx for idx in list if not any(punc in idx for punc in string.punctuation)]
print(str(list2))
输出:
['This', 'is', 'a', 'list']
如何使用列表理解删除字符串中的标点符号?
punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"
我知道如何使用 For 循环:
for i in text:
if i not in punctuations:
analyzed+=i
print(analyzed)
但是我如何使用列表理解来做到这一点?
punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"
试试这个:
>>[c for c in text if c not in punctuations]
您将获得:
['T', 'h', 'i', 's', ' ', 'i', 's', ' ', ' ', ' ', ' ', 'A', ' ', 'S', 't', 'r', 'i', 'n', 'g', ' ']
如果你想把它作为一个字符串,只需将它们全部连接起来即可。
>>''.join(c for c in text if c not in punctuations)
'This is A String '
使用生成器,并将其作为参数传递给 join()
以将结果转换回字符串。
analyzed = ''.join(c for c in text if c not in punctuations)
print(analyzed)
你可以先把你的标点和字符串转换成一个列表,然后再分开,如下:
import string
list = ["!", "This","@", "#", "$", "is", "%", "a", "^", "&", "list", "*", "(", ")"]
list2 = [idx for idx in list if not any(punc in idx for punc in string.punctuation)]
print(str(list2))
输出:
['This', 'is', 'a', 'list']