简体   繁体   English

Python如何从列表中的字符串中删除小写单词

[英]Python how to delete lowercase words from a string that is in a list

My question is: how do I delete all the lowercase words from a string that is an element in a list? 我的问题是:如何从列表中的元素字符串中删除所有小写单词? For example, if I have this list: s = ["Johnny and Annie.", "She and I."] 例如,如果我有此列表: s = ["Johnny and Annie.", "She and I."]

what do I have to write to make python return newlist = ["Johnny Annie", "She I"] 我必须写什么才能使python返回newlist = ["Johnny Annie", "She I"]

I've tried this, but it sadly doesn't work: 我已经尝试过了,但是可惜它不起作用:

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)

Iterate over the elements of the list and eliminate the words in lowercase. 遍历列表中的元素并消除小写字母。

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)
>>> s = ["Johnny and Annie.", "She and I."]

You can check if the word is lowercase using islower() and using split to iterate word by word. 您可以使用islower()并使用split逐个单词地检查单词是否为小写。

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

To remove punctuation as well 也要删除标点符号

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

Translate is not the right tool here. 翻译在这里不是正确的工具。 You can do it with a loop: 您可以循环执行此操作:

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

use filter with str.title if you just want the words starting with uppercase letters: 如果只希望以大写字母开头的单词,请使用带有str.title filter

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']

Or use a lambda not x.isupper to remove all lowercase words: 或者使用lambda而不是x.isupper删除所有小写单词:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM