【问题标题】:How to generate a list starting from a string and ending with another?如何生成从一个字符串开始并以另一个字符串结尾的列表?
【发布时间】:2019-05-24 13:28:31
【问题描述】:

我正在尝试从包含许多其他信息的文本文件中读取波长列表,但我不知道如何使 python 仅在“波长”之后才开始添加到列表中。但是,我可以让它在 } 结束。我确定我错过了一些非常明显的东西。我的文本文件有以这种格式存储的波长:

info1 = {xxx}
info2 = {xxx}

Wavelength = {
1.1,
2.2,
3.3
}

info3 = {
1.1,
2.2
}

我能够通过查找数据所在的行并在该范围内读取来将其读入列表,但我希望它更具适应性。

wavelength = []
with open(header, 'r') as hdr:
    for line in hdr:
        if 'wavlength' in line:
            #add next lines to list until }
            if float in line:
                if '}' in line:
                    break
    wavelength.append(line)
print(wavelength)

#output I want
[1.1,2.2,3.3]
#output I get
['}\n']

我知道如何删除特殊字符和新行,所以在我点击 } 之前我并不担心阅读下一行。

【问题讨论】:

    标签: python-3.x list file


    【解决方案1】:

    您可以遍历文件,并获取所有行,然后找到索引 Wavelength = { 和下一个 },然后选择它们之间的浮点数。 如果您想稍后使用这些行处理更多数据,获取所有行也会对您有所帮助

    wavelength = []
    
    with open('file.txt', 'r') as hdr:
        lines = [line.strip() for line in hdr.readlines() if line.strip()]
    
    #Find the index of Wavelength = {
    start_idx = lines.index('Wavelength = {')
    
    #Find the index of next }
    end_idx = lines.index('}',start_idx)
    
    #Get all floats between those indexes
    wavelength = [float(item.strip(',')) for item in lines[start_idx+1:end_idx]]
    print(wavelength)
    

    输出将是

    [1.1, 2.2, 3.3]
    

    【讨论】:

      【解决方案2】:

      一种方法是简单地检查当前行是否为数字。

      for line in hdr.splitlines():
          try:
              num = float(line)
          except ValueError:
              pass
          else:
              wavelength.append(num)
      

      不考虑括号和文件格式,但这可以通过设置布尔标志来实现。

      switch = False
      ...
      with open('file.txt', 'r') as hdr:
          for line in hdr.splitlines():
              if switch:
                  wavelength.append(num)
      
              if 'Wavelength' in line and '{' in line:
                  switch = True
              elif '}' in line:
                  switch = False
      

      如果你愿意,你可以使用正则表达式来整理它(例如re.search('Wavelength *{', line))。

      【讨论】:

        【解决方案3】:

        您可能想要跟踪您是否找到了“波长”。 您可以将其存储在名为found_wave_length 的变量中,该变量最初为False,但一旦找到它,就设置为True。仅当 found_wave_length 为真时才追加行。

        wavelength = []
        found_wave_length = False
        with open('file.txt', 'r') as hdr:
            for line in hdr:
                if 'Wavelength' in line:
                    found_wave_length = True
                    continue
        
                if found_wave_length and '}' in line:
                    break
        
                if found_wave_length:
                    #add next lines to list until }
                    wavelength.append(line)
        print(wavelength)
        

        【讨论】:

        • 尝试这个我只是得到一个空列表。这可能是因为我有高于和低于波长数据的数据。我更新了我的文本文件的样子。
        • 因为拼写很重要。在您的文件中 Wavelength 以大写字母 W 开头,但在代码中没有...
        • 对不起!这通常是我的失败,但即使进行了更正,由于某种原因,我仍然得到一个空列表。我对此很陌生,所以我敢肯定这是微不足道的。
        • 编辑了代码,忘记我的其他 cmets。当我找到} 时,我正在退出——即使那是在找到Wavelength 之前发生的。现在我断言found_wave_lengthbreak 退出循环之前为真。
        • 它仍然返回一个空列表,@Devesh Kumar Singh 的解决方案有效。我仍然很好奇我对你的代码做错了什么哈哈。谢谢!
        【解决方案4】:

        另一个没有任何循环的解决方案。所有字符串方法都可以链接在一起以保持紧凑性。

        with open(header, 'r') as f:
            s = f.read()
        temp = s.partition('Wavelength = {')[2] # Get everything after 'Wavelength = {'
        temp = temp.partition('}')[0]           # Get everything before the following '}'
        temp = temp.split(',\n')                # Separate individual numbers
        wavelength = [float(k) for k in temp]   # Convert to float
        

        【讨论】:

        • 不错。但是数组构造函数不是循环吗? ;)
        【解决方案5】:

        这是一个简单的简短版本。从 'Wavelength' 开始,在 '}' 结束,文件中有很多其他信息,就像你说的那样。

            wavelength = []
            flag = 0
            for line in open('wavefile.txt','r'):
                if '}' in line:
                    flag = 0
                if 'Wavelength' in line:
                    flag = 1
                    continue
                if flag == 1:
                    wavelength.append(line.strip())
        
            print(wavelength)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-04-10
          • 1970-01-01
          • 1970-01-01
          • 2013-08-23
          相关资源
          最近更新 更多