【问题标题】:Is there some way to ignore the punctuation in Python?有什么方法可以忽略 Python 中的标点符号吗?
【发布时间】:2021-02-12 15:22:11
【问题描述】:

请帮我解决以下问题:

有一个字符串:

Courses :- Thank You, Help me with this question, Have a good day

我想忽略“谢谢”和“课程”之间的任何标点符号。 我现在正在做的是:

        if "Courses" in c:
        print(c)
        idx = c.index('-')
        while not c[idx].isalpha():
            idx += 1
        old_courses = c[idx:]
        print(old_courses)      

我可以得到:谢谢,帮我解决这个问题,祝你有美好的一天

但“谢谢”和“课程”之间会有任何其他标点符号。我该怎么做才能得到与上面相同的东西?也许可以使用字符串模块。

谢谢!!!

【问题讨论】:

  • 一种简单的方法是遍历所有字符并仅选择要保留的字符,然后从中重建字符串。只需很少的额外知识,这应该是可行的,基本上只有循环。这不一定是最有效的方法,但很容易记下来。
  • 你可以试试string.split(' ')是结构是Course XX some text
  • 在这种情况下它将是' '.join(c.split(' ')[2:])

标签: python python-3.x string


【解决方案1】:

我会这样做

>>> s = "Courses :- Thank you, Help me with this question"
>>> punctuations = ['.',',',':','-']
>>> newstr = [x for x in s if not x in punctuations]
>>> newstr = ''.join(newstr)
>>> newstr
'Courses  Thank you Help me with this question'

您可能希望字符串中包含空格和数字。这就是我没有使用 isalpha 方法的原因。最好列出要删除的字符(或保留任何更容易的字符)。

希望我能理解您的需求

【讨论】:

    【解决方案2】:

    使用正则表达式的解决方案

    import re
    import string
    
    s = 'Courses :- Thank You, Help me with this question, Have a good day'
    
    re.compile(f'[{re.escape(string.punctuation)}]').sub('', s)
    
    'Courses  Thank You Help me with this question Have a good day'
    

    【讨论】:

      【解决方案3】:

      如果该字符串的格式与符号无关,请尝试此操作。

      if "Courses" in c:
          new_c = ' '.join(c.split()[2:])
          print(new_c)
      

      【讨论】:

        【解决方案4】:

        您可以使用内置的string.replace() 函数或正则表达式模块。

        这里有更多信息的好答案:

        Best way to replace multiple characters in a string?

        Python strip() multiple characters?

        【讨论】:

          【解决方案5】:

          您可以使用字符类匹配单词之间的所有标点符号或空格,以使用\s*[:-][\s:-]* 匹配至少一个字符:-,并将单词分成两组。

          在替换中使用两个组,中间有一个空格。

          import re
          c = "Courses :- Thank You, Help me with this question, Have a good day"
          result = re.sub(r"\b(Courses)\s*[:-][\s:-]*\b(Thank You)\b", r"\1 \2", c)
          print(result)
          

          输出

          Courses Thank You, Help me with this question, Have a good day
          

          或者在替换中使用环视和一个空格。

          import re
          c = "Courses :- Thank You, Help me with this question, Have a good day"
          result = re.sub(r"(?<=\bCourses)\s*[:-][\s:-]*(?=\bThank You\b)", r" ", c)
          print(result)
          

          【讨论】:

            猜你喜欢
            • 2015-08-11
            • 1970-01-01
            • 2014-12-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-11-19
            • 1970-01-01
            相关资源
            最近更新 更多