【问题标题】:How to remove marks from string and turn it into a list如何从字符串中删除标记并将其变成列表
【发布时间】:2019-04-24 09:49:50
【问题描述】:

我需要创建一个函数,将字符串转换为不带!?., %#$ . 且不带大写字母的列表。最后的字符串只是一个例子,所以它需要返回['mr', 'stark', 'i', "don't", 'feel', 'so', 'good']

谁能告诉我为什么我的代码打印None

def sentence_to_words(s):
    # Write the rest of the code for question 2 below here.
    s_new= []
    s1 = s.split()
    a = ['#',',','!','.','?','$']
    for i in s.split():
        if i in a:
            s2 = s1.remove(i)
            s_new = s_new.append(s2)
            return s_new
print sentence_to_words("Mr. Stark... I don't feel so good")

【问题讨论】:

  • 你的方法有什么问题?
  • 它不会在列表中的任何值上运行.. 它只是不打印
  • 我认为您的 return 不应该在 if 语句中。
  • for i in s.split(): 中,您正在检查单词的每个单词并查看它是否在a 中。您应该查看a 的元素是否在s 中。

标签: string python-2.7 list split append


【解决方案1】:

我不能很好地理解您的代码,但是使用re.subsplit() 的替代方法在哪里。 我们首先使用re.sub 删除任何特殊字符,然后使用split 获取单词列表,即:

import re
sentence = "Mr. Stark... I don't feel so good"
words = re.sub(r"[#,!\?\$.]", "", s).split()

使用re.split

words = re.split("[^a-z'-]+", sentence, 0, re.IGNORECASE)

两个示例输出:

# ['Mr', 'Stark', 'I', 'don't', 'feel', 'so', 'good']   

Ideone Demo

【讨论】:

    【解决方案2】:

    调试此问题的最佳方法是验证您对程序状态的假设是否适用于每个步骤。在您确定每一行代码都符合您的预期之前,请不要跳过。在循环中添加 print 可以准确显示每次迭代中 i 的内容:

    Mr.
    Stark...
    I
    don't
    feel
    so
    good
    

    a = ['#',',','!','.','?','$'] 中没有这些词,因此循环内的条件块永远不会运行。循环结束后,您的程序会返回None,当没有指定返回值时,Python 函数会返回这些函数。

    此外,您的条件块操作未按预期工作;检查返回值,如果它们是就地操作,例如.append(),则避免进行分配,它返回None,不应分配给任何东西。此外,如果if 块确实执行,它将过早地return 结果而不完成列表其余部分的工作。

    您可能正在寻找这样的东西:

    def sentence_to_words(s):
        s_new = []
        ignore = ["#", "!", ",", ".", "?", "$"]
    
        for word in s.split():
            cleaned_word = ""
    
            for letter in list(word):
                if letter not in ignore:
                    cleaned_word += letter
    
            s_new.append(cleaned_word.lower())
    
        return s_new
    
    
    print sentence_to_words("Mr. Stark... I don't feel so good")
    

    输出:

    ['mr', 'stark', 'i', "don't", 'feel', 'so', 'good']
    

    上面例子中的做法是对单词进行迭代,然后对每个单词中的字母进行迭代,按照要求清理它们,并将清理的单词添加到结果数组中。请注意有助于理解程序的描述性变量名称(例如,i 实际上是代码中的一个词,但 i 通常表示整数或索引)。

    上面的例子可以优化——它使用了很多容易出错的数组和循环,忽略列表应该是一个参数,以使函数可重用,in 运算符在列表上很慢(ignore应该是一组)。使用正则表达式使其成为单行:

    import re
    
    def sentence_to_words(s):
        return re.sub(r"[\#\,\!\.\?\$]", "", s).lower().split()
    

    或者使用filter 和要忽略的字符列表作为默认参数:

    def sentence_to_words(s, ignore=set("#!,.?$")):
        return filter(lambda x: x not in ignore, s).lower().split()
    

    Try it!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 2010-09-19
      • 2017-09-06
      相关资源
      最近更新 更多