【问题标题】:Removing all spaces, punctuation, and capitalization [duplicate]删除所有空格、标点符号和大写[重复]
【发布时间】:2019-08-25 02:04:29
【问题描述】:

我们正在计算机科学课上研究 Vigenere 密码,老师希望我们采取的第一步是删除字符串中的所有空格、标点符号和大写字母。

#pre-process - removing spaces, punctuation, and capitalization
def pre_process(s):
    str = s.lower()
    s = (str.replace(" ", "") + str.replace("!?'.", ""))
    return s
print(pre_process("We're having a surprise birthday party for Eve!"))

我想要的输出是"werehavingasurpisebirthdaypartyforeve",但我实际得到的是"we'rehavingasurprisebirthdaypartyforeve!we're having a surprise birthday party for eve!"

【问题讨论】:

  • str.replace("!?'.", "") 看起来替换了确切的模式!?'.。请参阅this post 了解如何替换多个字符。

标签: python string vigenere


【解决方案1】:

您应该使用正则表达式而不是字符串替换。试试这个代码。

import re
mystr="We're having a surprise birthday party for Eve!"
#here you can pass as many punctuations you want
result=re.sub("[.'!#$%&\'()*+,-./:;<=>?@[\\]^ `{|}~]","",mystr)
print(result.lower())

【讨论】:

    【解决方案2】:

    str.replace("!?'.", "")) 仅替换字符串 !?'.,而不是四个字符中的任何一个。

    您需要对每个字符使用单独的替换调用,或者使用正则表达式。

    【讨论】:

      【解决方案3】:

      您的解决方案不起作用的原因是它试图删除文字字符串“!?'。”,而不是单独删除每个字符。

      实现此目的的一种方法如下:

      import re
      
      regex = re.compile('[^a-zA-Z]')
      
      s = "We're having a surprise birthday party for Eve!"
      s = regex.sub('', s).lower()
      

      【讨论】:

        【解决方案4】:
        import re
        
        def preprocess(s):
            return re.sub(r'[\W_]', '', s).lower()
        

        re.sub 删除所有非字母数字字符(A-Z 和 0-9 除外)。

        lower() 删除大写。

        【讨论】:

          【解决方案5】:

          一种不使用 RegEx 的方法。

          >>> import string
          >>> s
          "We're having a surprise birthday party for Eve!"
          >>> s.lower().translate(None, string.punctuation).replace(" ", "")
          'werehavingasurprisebirthdaypartyforeve'
          

          【讨论】:

            【解决方案6】:

            更改您的代码如下:-

            def pre_process(s):
              str = s.lower()
              s = (str.replace(" ", ""))
              s= s.replace("!", "")
              s= s.replace("'", "")
              return s
            print(pre_process("We're having a surprise birthday party for Eve!"))
            

            【讨论】:

              【解决方案7】:

              str.translate 也是一个选项。您可以使用str.maketrans 创建一个转换表,其中第一个参数 (ascii_uppercase) 将被转换为第二个参数 (ascii_lowercase)。第三个参数 (punctuation + whitespace) 是您要删除的字符的列表:

              from string import ascii_lowercase, ascii_uppercase, punctuation, whitespace
              
              table = str.maketrans(ascii_uppercase, ascii_lowercase, punctuation + whitespace)
              s = "We're having a surprise birthday party for Eve!"
              print(s.translate(table))
              # werehavingasurprisebirthdaypartyforeve
              

              一旦你初始化了table,每个后续的字符串都可以通过应用进行转换

              s.translate(table)
              

              【讨论】:

                【解决方案8】:

                你可以使用re ?,

                >>> import re
                >>> x
                "We're having a surprise birthday party for Eve!"
                >>> re.sub(r'[^a-zA-Z0-9]', '', x).lower() # negate the search. Fastest among the two :)
                'werehavingasurprisebirthdaypartyforeve'
                

                list comprehension

                >>> import string
                >>> ''.join(y for y in x if y in string.ascii_letters).lower()
                'werehavingasurprisebirthdaypartyforeve'
                

                只是一个基准,

                >>> timeit.timeit("''.join(y for y in x if y in string.ascii_letters).lower()", setup='import string;x = "We\'re having a surprise birthday party for Eve!"')
                7.747261047363281
                >>> timeit.timeit("re.sub(r'[^a-zA-Z0-9]', '', x).lower()", setup='import re;x = "We\'re having a surprise birthday party for Eve!"')
                2.912994146347046
                

                【讨论】:

                • 别忘了把所有东西都变成小写!
                猜你喜欢
                • 1970-01-01
                • 2021-12-20
                • 2014-12-26
                • 1970-01-01
                • 1970-01-01
                • 2011-08-16
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多