计算第一项中另一个列表中列表中的单词

时间:2017-12-02 23:18:21

标签: python python-3.x list count

HY, 我想从位置零的另一个列表中的列表中计算给定的短语。

list_given_atoms= ['C', 'Cl', 'Br']
list_of_molecules= ['C(B2Br)[Cl{H]Cl}P' ,'NAME']

当python找到匹配项时,应该在

这样的字典中进行安全保护
countdict = [ 'Cl : 2', 'C : 1', 'Br : 1'] 

我试过

re.findall(r'\w+', list_of_molecules[0])

已经,但结果就像" B2Br",这绝对不是我想要的。

有人可以帮助我吗?

5 个答案:

答案 0 :(得分:1)

应使用

[a-zA-Z]+代替\w+,因为\w+会匹配字母和数字,而您只是在寻找字母:

import re
list_given_atoms= ['C', 'Cl', 'Br']
list_of_molecules= ['C(B2Br)[Cl{H]Cl}P' ,'NAME']
molecules = re.findall('[a-zA-Z]+', list_of_molecules[0])
final_data = {i:molecules.count(i) for i in list_given_atoms}

输出:

{'C': 1, 'Br': 1, 'Cl': 2}

答案 1 :(得分:1)

您可以使用以下内容:

>>> Counter(re.findall('|'.join(sorted(list_given_atoms, key=len, reverse=True)), list_of_molecules[0]))
Counter({'Cl': 2, 'C': 1, 'Br': 1})

您必须按其长度对元素进行排序,因此'Cl''C'之前匹配。

答案 2 :(得分:0)

re.findall()解决方案:

import re

list_given_atoms = ['C', 'Cl', 'Br']
list_of_molecules = ['C(B2Br)[Cl{H]Cl}P' ,'NAME']
d = { a: len(re.findall(r'' + a + '(?=[^a-z]|$)', list_of_molecules[0], re.I)) 
      for a in list_given_atoms }

print(d)

输出:

{'C': 1, 'Cl': 2, 'Br': 1}

答案 3 :(得分:0)

我尝试了你的解决方案,我发现,彼此之后还有几个C.所以我来到这里:

for element in re.findall(r'([A-Z])([a-z|A-Z])?'. list_of_molecules[0]):
    if element[1].islower:
        counter = element[0] + element[1]
        if not (counter in counter_dict):
            counter_dict[counter] = 1
        else:
            counter_dict[counter] += 1

我只用一个案例检查元素并将它们添加到字典中的方式相同。可能有更好的方法。

答案 4 :(得分:0)

您不能使用/w作为单词字符相当于:

[a-zA-Z0-9_]

明确包含数字,因此"B2Br"匹配。

你也不能只使用正则表达式:

[a-zA-Z]+

因为这会产生一个像"CO2"这样的原子,它应该产生2个独立的分子:C0

然而,我提出的正则表达式(regex101)只检查大写字母,然后检查01(所以可选的)小写字母。

这是:

[A-Z][a-z]{0,1}

它会正确地产生原子。

所以要将其合并到原来的lists

list_given_atoms= ['C', 'Cl', 'Br']
list_of_molecules= ['C(B2Br)[Cl{H]Cl}P' ,'NAME']

我们首先要找到list_of_molecules中的所有原子,然后在list_given_atoms中创建一个原子计数字典。

为了找到所有原子,我们可以在分子列表的第一个元素上使用re.findall

atoms = re.findall("[A-Z][a-z]{0,1}", list_of_molecules[0])

给出list

['C', 'B', 'Br', 'Cl', 'H', 'Cl', 'P']

然后,为了获得字典中的计数,我们可以使用dictionary-comprehension

counts = {a: atoms.count(a) for a in list_given_atoms}

给出了所需的结果:

{'Cl': 2, 'C': 1, 'Br': 1}

当我们有CO2等分子时,它们也会起作用。