【问题标题】:Python function to replace letters替换字母的Python函数
【发布时间】:2020-05-25 14:05:46
【问题描述】:

我需要删除标点符号,我将问题放在下面的代码中。我不确定什么不起作用以及我缺少什么 - 我试图让它尽可能基本/简单,并且只使用我迄今为止学到的初学者的东西。它说要使用 replace() 所以这就是我试图做的。谢谢!

定义一个名为 strip_punctuation 的函数,它接受一个参数,一个代表单词的字符串,并从单词中的任何地方删除被认为是标点符号的字符。 (提示:记住字符串的 .replace() 方法。)

def strip_punctuation(punctuations):
punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
for item in punctuations:
    if item in punctuation_chars:
        punctuations.replace(item, "")           
return punctuations

【问题讨论】:

  • punctuations 由什么组成?字符串列表?
  • 哦,是的 - 标点符号应该是一个字符串。只是一个字符串。我应该给它起不同的名字。
  • 它的哪一部分不起作用?主要问题是什么? (还记得缩进你的代码)

标签: python replace punctuation


【解决方案1】:

Python 字符串是不可变的。 str.replace 不修改字符串,它返回一个 new 字符串。所以你想要

punctuations = punctuations.replace(item, "")

请注意,没有必要事先检查item 是否在punctuations 中,如果没有找到搜索字符串,replace 什么也不做。

【讨论】:

    【解决方案2】:
    def strip_punctuation(x):
        punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
        for ch in punctuation_chars:
            x=x.replace(ch,"")
        return x
    

    这会起作用。

    【讨论】:

      【解决方案3】:

      (此函数读取一个字符串并检查它,该字符串是否具有列表中存在的标点符号 (punctuation_chars) 然后它将用空字符串替换标记,因此在函数完成其任务后它将返回一个没有 punctuation_chars 的字符串)

      punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
      
      def strip_punctuation (word):
      
          new_word = ""
          for w in word:
              if w in punctuation_chars :
                  y= w.replace(w,"")
                  new_word = new_word+y
              else:
                  new_word = new_word+w
      
          return new_word
      

      【讨论】:

      • 嗨,如果您提供代码作为答案,也可以解释一下它是如何工作的以及为什么它可以解决问题中的问题
      • 嗨,一般来说,这个函数读取一个字符串并检查它,这个字符串是否具有列表中存在的标点符号(punctuation_chars)然后它将用空字符串替换标记,所以在函数完成后任务它将返回一个没有 punctuation_chars 的字符串。这是你问的吗??
      • 嗨,我建议编辑您的答案并在评论中添加您刚刚给我的解释。
      • 这里是新的 :),我尝试了很多次,但他们拒绝了,你能告诉我怎么写吗
      • 老实说,不确定您是否可以在开始时编辑答案
      【解决方案4】:
      def strip_punctuation(x):
          punctuation_chars = ["'", '"', ",", ".", "!", ":", ";", '#', '@']
          for char in x:
              if char in punctuation_chars:
                  x=x.replace(char, ' ')
                  x=x.replace(' ','')
          return x
      
      print(strip_punctuation('he.llo,'))
      

      试试这个,我确保消除字符串中的标点符号

      【讨论】:

        【解决方案5】:

        我认为一切都不同......但不要使用替换:

        def strip_punctuation(x):
            palabra = ""
            for chr in x:
                if chr not in punctuation_chars:
                    palabra += chr 
            return palabra
        

        更加一致。和小。

        【讨论】:

          猜你喜欢
          • 2011-12-18
          • 2020-01-31
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-06-24
          • 2017-11-05
          • 2016-12-22
          • 1970-01-01
          相关资源
          最近更新 更多