【问题标题】:How To Remove Punctuation In String Using List Comprehension?如何使用列表理解删除字符串中的标点符号?
【发布时间】:2021-04-17 06:46:45
【问题描述】:

如何使用列表理解去除字符串中的标点符号?

punctuations="!@#$%^&*()_-=+:;{}[]<>,.?/\''"
analyzed=""
text="This is ;;;; $# @#%@$ A String <>?::"

我知道如何使用 For 循环:

for i in text:
     if i not in punctuations:
          analyzed+=i
print(analyzed)

但是如何使用列表理解来做到这一点?

【问题讨论】:

  • 你尝试了什么?
  • 我试过了:print([analyzed+=i for i in punctuations if i in text])
  • 使用带有条件的列表推导,并将其作为参数传递给''.join()
  • 你倒退了。 for i in text if i not in punctuations
  • i 打印的是什么?你不想要analyzed 吗?

标签: python arrays list list-comprehension


【解决方案1】:

使用生成器,并将其作为参数传递给join(),以将结果转换回字符串。

analyzed = ''.join(c for c in text if c not in punctuations)
print(analyzed)

【讨论】:

    【解决方案2】:
    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 '
    

    【讨论】:

      【解决方案3】:

      你可以先把你的标点和字符串转换成一个列表,然后分开,如下:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-11
        • 1970-01-01
        • 2013-10-08
        相关资源
        最近更新 更多