如何从python中的字符串中删除小写字词
问题描述:
我是python中的新成员,我遇到了一些问题。如何从python中的字符串中删除小写字词
我有一个数组(或它在Python的说列表)是这样的:
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
正如你看到的这个数组的每个元素都包含了一些话。这些词都是小写和大写。
如何从这个数组中删除每个小写字母?
比如我想有作为的结果这份名单:
list = [ 'NICE' , 'FLOWER' , 'GOOD' , 'YELLOW']
答
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
output = [' '.join(w for w in a.split() if w.isupper()) for a in l]
# or:
output = [' '.join(filter(str.isupper, a.split())) for a in l]
回报:(不要使用list
变量名)
['NICE', 'FLOWER', 'GOOD', 'YELLOW']
+0
谢谢你它工作很好:) – gaggina
答
以下将做到这一点:
def remove_lower(s):
return ' '.join(w for w in s.split(' ') if not w.islower())
l = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
l = map(remove_lower, l)
答
这里是一种与re
(正则表达式)模块,以做到这一点:
list = map(lambda l: re.sub(r'\b\w*[a-z]+\w*\b','',l).strip(), list)
答
list = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
print [word for pair in list for word in pair.split() if not word.islower()]
答
lst = [ 'NICE dog' , 'blue FLOWER' , 'GOOD cat' , 'YELLOW caw']
for i in range(len(lst)):
tmp = ""
for j in range(len(lst[i])):
if ord(lst[i][j]) <= ord('Z'):
tmp = tmp + lst[i][j]
lst[i] = tmp.strip()
print(lst) #['NICE', 'FLOWER', 'GOOD', 'YELLOW']
答
string.translate()
将迅速删除指定的字符:
>>> import string
>>> mylist=['NICE dog', 'blue FLOWER', 'GOOD cat', 'YELLOW caw']
>>> print [s.translate(None, string.ascii_lowercase) for s in mylist]
['NICE', 'FLOWER', 'GOOD', 'YELLOW']
不覆盖内置'list'! – moooeeeep
你需要考虑混合大小写的单词吗?例如,'NICE小狗'。这些应该如何处理? –
如果字符串是“尼斯小狗”,我只想回顾'尼斯' – gaggina