簡體   English   中英

使用正則表達式查找字符串中所有小寫字母追加到列表。 蟒蛇

[英]Using regex to findall lowercase letters in string append to list. Python

我正在尋找一種從具有大寫字母和可能小寫字母的字符串中獲取小寫字母值的方法

這是一個例子

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

聽起來像(我可能會誤解你的問題),你只需要捕獲的小寫字母的運行 ,而不是每個單獨的小寫字母。 這很容易:只需在正則表達式中添加+量詞即可。

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

+量詞指定您希望“至少一個,並且可以在一行中找到盡可能多”的前一個表達式(在本例中為'[az]' )。 因此,這將捕獲所有小寫字母的全部內容,並將它們全部組合在一起,這將使它們在輸出列表中顯示為您希望的樣子。

如果您想保留列表結構並獲取索引,則會有些麻煩,但這仍然非常簡單:

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], []]

除了正則表達式,您還可以在此處使用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], []]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM