[英]Count the number letter occurrences in a string
我想在 python 中編寫分子式(字符串)中原子數的摘要。 該字符串是一個字母后跟一個數字(當沒有數字時,它被計為一個)。
輸入:C3H7NO2C3H7NO2S Output:C6H14N2O4S
我僅有的字母是:O、C、N、H 和 S。
一個 C# “oneliner” 你當然不能作為家庭作業解決方案發送:
var s = "C3H7NO2C3H7NO2S";
var s2 = string.Join(" ",Regex.Split(s, @"([A-Z]\d*)")
.Where(x => !string.IsNullOrEmpty(x))
.Select(x => Regex.Match(x, @"([A-Z])(\d*)"))
.Select(m => new {elt = m.Groups[1].Value, cnt = m.Groups.Count > 2 ? m.Groups[2].Value : "1"})
.Select(e => new {e.elt, cnt = string.IsNullOrEmpty(e.cnt) ? 1 : int.Parse(e.cnt)})
.GroupBy(e => e.elt)
.Select(g => $"{g.Key}{g.Sum(x=>x.cnt)}")
);
// s2 contains "C6 H14 N2 O4 S1"
定義轉換(aa_seq):
temp = re.findall('\d+|\D+', str_atoms) #split string to numbers and chars
#print(temp)
# dictionary
dicta = {}
# list to dictionary
for i in range(int(0.5 * len(temp))):
key = temp[2 * i] # set atom as key
val = int(temp[2 * i + 1]) #set value as the number that follows
# print(key + ' = ' + str(val))
if (key in dicta): #add value to existing key
dicta[key] += val
else: # if key does not exist create this
dicta[key] = val
print(dicta)
# dictionary to string
final_str = ''
for x in dicta:
final_str += x + str(dicta[x])
print(str_atoms)
print(final_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.