![](/img/trans.png)
[英]Python - using regex to search for a string then append each match to a new list
[英]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.