【问题标题】:Python how to get rid of lowercase elements inside a listPython如何摆脱列表中的小写元素
【发布时间】:2015-01-02 06:26:09
【问题描述】:

这是我当前的代码:

def poisci_pare(besedilo):        
    sents = besedilo.split('.')
    noviseznam = [sent.split() for sent in sents if sent]
    return noviseznam

这会返回:

poisci_pare("You are cool Anna. Johnny and I.")
>>>output: [["You", "are", "cool", "Anna"], ["Johnny", "and", "I"]]

如何更改我的函数,使其删除小写单词并返回仅包含大写单词的列表?例如我想做到这一点:

poisci_pare("You are cool Anna. Johnny and I.")
>>>output: [["You","Anna"], ["Johnny", "I"]]

【问题讨论】:

    标签: python list lowercase


    【解决方案1】:

    给定一个大小写混合的单词列表:

    words = ["You", "are", "cool", "Anna"]
    

    您可以通过推导排除小写字母:

    words = [word for word in words if not word.islower()]
    

    【讨论】:

    • 这不行,因为我必须在一个列表中有一个列表,我有[[“你”,“是”,“酷”,“安娜”]],我该怎么做继续为现有列表中的列表执行此操作?
    【解决方案2】:

    这是我尝试过的:

     s = "You are cool Anna. Johnny and I."
     [ re.findall('[A-Z][a-z]*',x) for x in s.split('.')[:-1] ]
    

    输出:

    [['You', 'Anna'], ['Johnny', 'I']]
    

    提供sentence 总是以'.'结尾

    【讨论】:

    • 它有时会起作用,但是当我把它作为一个字符串(这是在斯洛文尼亚语中,我必须用这些句子测试我的评估)它不起作用,如果你尝试把 s = 'Na vratih sta se prva pojavila Ana in Peter, menda "slučajno"。 Peter se je sicer več vrtel okrog Nives。它返回: [['Na', 'Ana', 'Peter,', 'Peter', 'Nives']] 这是怎么回事?句子中的“”会是问题吗?
    • @NejcPisk Python 2 还是 Python 3?字节字符串还是 Unicode 字符串?根据这些,č 也可能是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2019-05-06
    • 2021-09-01
    • 1970-01-01
    • 2019-03-22
    相关资源
    最近更新 更多