【问题标题】:How to retrieve specific information from a list in python?如何从python中的列表中检索特定信息?
【发布时间】:2018-09-06 13:56:01
【问题描述】:

我有一个文件,我想从中检索特定信息。

首先,我提取了感兴趣的行并将它们放在一个列表中:

array = []
file_in = open("Traj.pdb", "r")
  for line in file_in:
      if line.startswith('TITLE'):
          array.append(line)

我最终得到一个这样的列表:

['TITLE 蛋白质疯狂!膜 UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500000.00000\n', 'TITLE 疯狂中的蛋白质!膜 UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500020.00000\n', 'TITLE 疯狂中的蛋白质!膜 UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500040.00000\n']

我想提取“t=”信息(t= 1500000.00000, t= 1500020.00000, t= 1500040.00000 ...等),但我不知道该怎么做。如您所见,我列表的元素是句子,在这种情况下我对如何检索特定信息有点困惑。非常感谢您的帮助或建议。

【问题讨论】:

  • 看来你需要array.append(line.strip().split('=')[-1])代替

标签: python


【解决方案1】:

t= 上拆分您的列表,它会给您左右两半。您只需要右半部分,即t= 之后的内容。另外,请确保删除右半部分末尾的换行符\n

l = ['TITLE Protein in INSANE! Membrane UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500000.00000\n', 'TITLE Protein in INSANE! Membrane UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500020.00000\n', 'TITLE Protein in INSANE! Membrane UpperLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 LowerLeaflet>POPC:POPE:CHOL=31.0:41.0:28.0 t= 1500040.00000\n']
result = []
for line in l:
    splitted_arr = line.split("t= ")
    # Consider only the right half
    splitted_arr = splitted_arr[1]
    # Remove the last character i.e \n
    splitted_arr = splitted_arr[:len(splitted_arr)-1]
    result.append(splitted_arr)
print(result)

【讨论】:

    【解决方案2】:

    试试这个:

    import re
    
    array_with_elements_i_want = []
    
    for elem in array:
        array_with_elements_i_want.append(re.search(r"t= (.)*", elem).group(0))
    

    甚至更好:

    import re
    
    array_with_elements_i_want = []
    
    for elem in array:
        v = re.search(r"t= (.)*", elem)
        if v is not None:
            array_with_elements_i_want.append(v.group(0))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-31
      • 1970-01-01
      • 2016-01-23
      • 2016-08-31
      • 1970-01-01
      相关资源
      最近更新 更多