【问题标题】:Python how to delete lowercase words from a string that is in a listPython如何从列表中的字符串中删除小写单词
【发布时间】:2015-01-02 01:34:00
【问题描述】:

我的问题是:如何从作为列表元素的字符串中删除所有小写单词?例如,如果我有这个列表:s = ["Johnny and Annie.", "She and I."]

我要写什么才能让python返回newlist = ["Johnny Annie", "She I"]

我试过了,可惜没用:

def test(something):
    newlist = re.split("[.]", something)
    newlist = newlist.translate(None, string.ascii_lowercase)
    for e in newlist:
        e = e.translate(None, string.ascii_lowercase)

【问题讨论】:

    标签: python string list lowercase


    【解决方案1】:
    >>> s = ["Johnny and Annie.", "She and I."]
    

    您可以使用islower() 检查单词是否为小写,并使用split 逐字迭代。

    >>> [' '.join(word for word in i.split() if not word.islower()) for i in s]
    ['Johnny Annie.', 'She I.']
    

    同时删除标点符号

    >>> import string
    >>> [' '.join(word.strip(string.punctuation) for word in i.split() if not word.islower()) for i in s]
    ['Johnny Annie', 'She I']
    

    【讨论】:

      【解决方案2】:

      翻译在这里不是正确的工具。你可以用循环来做到这一点:

      newlist = []
      for elem in s:
          newlist.append(' '.join(x for x in elem.split(' ') if x.lower() == x))
      

      【讨论】:

        【解决方案3】:

        如果您只想要以大写字母开头的单词,请使用 filterstr.title

        from string import punctuation
        
        s = ["Johnny and Annie.", "She and I."]
        
        print([" ".join(filter(str.istitle,x.translate(None,punctuation).split(" "))) for x in s])
        ['Johnny Annie', 'She I']
        

        或者使用 lambda 而不是 x.isupper 来删除所有小写单词:

        [" ".join(filter(lambda x: not x.isupper(),x.translate(None,punctuation).split(" "))) for x in s]
        

        【讨论】:

          【解决方案4】:

          遍历列表的元素并消除小写单词。

          s = s = ["Johnny and Annie.", "She and I."]
          for i in s:
              no_lowercase = ' '.join([word for word in i.split(' ') if not word.islower()])
              print(no_lowercase)
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2011-02-02
            • 2011-03-31
            • 1970-01-01
            • 1970-01-01
            • 2017-08-19
            • 1970-01-01
            • 2023-02-02
            • 2022-01-26
            相关资源
            最近更新 更多