使用正则表达式查找字符串中的所有小写字母附加到列表。蟒蛇

时间:2013-04-04 21:00:35

标签: python regex string lowercase findall

我正在寻找一种方法来从包含大写和可能小写字母的字符串中获取小写值

这是一个例子

sequences = ['CABCABCABdefgdefgdefgCABCAB','FEGFEGFEGwowhelloFEGFEGonemoreFEG','NONEARELOWERCASE'] #sequences with uppercase and potentially lowercase letters

这就是我要输出的内容

upper_output = ['CABCABCABCABCAB','FEGFEGFEGFEGFEGFEG','NONEARELOWERCASE'] #the upper case letters joined together
lower_output = [['defgdefgdefg'],['wowhello','onemore'],[]] #the lower case letters in lists within lists
lower_indx = [[9],[9,23],[]] #where the lower case values occur in the original sequence

所以我希望lower_output列表是SUBLISTS的列表。 SUBLISTS将包含所有小写字母的字符串。

我正在考虑使用正则表达式。 。 。

import re

lower_indx = []

for seq in sequences:
    lower_indx.append(re.findall("[a-z]", seq).start())

print lower_indx

对于我正在尝试的小写列表:

lower_output = []

for seq in sequences:
    temp = ''
    temp = re.findall("[a-z]", seq)
    lower_output.append(temp)

print lower_output

但是值不在单独的列表中(我仍然需要加入它们)

[['d', 'e', 'f', 'g', 'd', 'e', 'f', 'g', 'd', 'e', 'f', 'g'], ['w', 'o', 'w', 'h', 'e', 'l', 'l', 'o', 'o', 'n', 'e', 'm', 'o', 'r', 'e'], []]

2 个答案:

答案 0 :(得分:2)

听起来(我可能误解了你的问题)你只需要捕获小写字母的运行,而不是每个单独的小写字母。这很简单:只需将+量词添加到正则表达式中即可。

for seq in sequences:
    lower_output.append(re.findall("[a-z]+", seq)) # add substrings

+量词指定您想要前面表达式中的“至少一个,并且连续找到的数量”(在本例中为'[a-z]')。因此,这将在一个组中捕获您的全部小写字母,这应该使它们在您的输出列表中显示为您希望它们。

如果你想保留你的列表列表结构并获得索引,它会变得有点大,但它仍然很简单:

for seq in sequences:
    matches = re.finditer("[a-z]+", seq) # List of Match objects.
    lower_output.append([match.group(0) for match in matches]) # add substrings
    lower_indx.append([match.start(0) for match in matches]) # add indices

print lower_output
>>> [['defgdefgdefg'], ['wowhello', 'onemore'], []]

print lower_indx
>>> [[9], [9, 23], []]

答案 1 :(得分:0)

除正则表达式外,您还可以在此处使用itertools.groupby

In [39]: sequences = ['CABCABCABdefgdefgdefgCABCAB','FEGFEGFEGwowhelloFEGFEGonemoreFEG','NONEARELOWERCASE'] #sequences with uppercase and potentially lowercase letters

In [40]: lis=[["".join(v) for k,v in groupby(x,key=lambda z:z.islower())] for x in sequences]

In [41]: upper_output=["".join(x[::2]) for x in lis]

In [42]: lower_output=[x[1::2] for x in lis]

In [43]: upper_output
Out[43]: ['CABCABCABCABCAB', 'FEGFEGFEGFEGFEGFEG', 'NONEARELOWERCASE']

In [44]: lower_output
Out[44]: [['defgdefgdefg'], ['wowhello', 'onemore'], []]

In [45]: lower_indx=[[sequences[i].index(y) for y in x] for i,x in enumerate(lower_output)]

In [46]: lower_indx
Out[46]: [[9], [9, 23], []]