【问题标题】:How to xtract multiple numbers delimited by brackets from a txt document into a python list?如何从txt文档中提取由括号分隔的多个数字到python列表中?
【发布时间】:2021-08-27 14:11:09
【问题描述】:

所以我有一个 .txt 文件,如下所示:

[some_strings] id:[1227194]
[some_strings] id:[1227195]
[some_strings] id:[1227196]

我需要做的是提取括号 [] 之间的所有数字并将它们附加到一个列表中,然后我将使用该列表进行进一步分析。 最终结果应该是:

list = [1227194,1227195,1227196]

实现这一目标的最 Pythonic 方式是什么?

【问题讨论】:

标签: python list text text-extraction


【解决方案1】:

试试这个:

import re

filename = 'text.txt'

with open(filename) as file:
    lines = file.readlines()
    lines = " ".join(line.rstrip() for line in lines)    
    num_list = re.findall('\d+',lines)
num_list

输出:

['1227194', '1227195', '1227196']

【讨论】:

    【解决方案2】:

    正则表达式解释here

    import re
    
    s = """[some_strings] id:[1227194]
    [some_strings] id:[1227195]
    [some_strings] id:[1227196]"""
    
    l = re.findall(r'\[(\d+)\]', s, re.MULTILINE)
    print(l) #['1227194', '1227195', '1227196']
    

    【讨论】:

      【解决方案3】:

      您可以使用.split,另一种方法是使用正则表达式:

      s = """
      [some_strings] id:[1227194]
      [some_strings] id:[1227195]
      [some_strings] id:[1227196]
      """
      
      [line.rstrip(']').split('[')[-1] for line in s.split('\n') if line != '']
      # Out[95]: ['1227194', '1227195', '1227196'
      

      【讨论】:

        【解决方案4】:

        我认为的一种方式是:

        ids = []
        with open(text.txt) as file:
           for line in file.readlines():
               id_with_bracket = split('id:[')
               ids.append(int(id_with_bracket[:-1]))
        

        【讨论】:

          【解决方案5】:
          import re
          with open('text.txt', 'r') as f:
               data = re.findall('\d+',f.read())
          
          
          ['1227194', '1227195', '1227196']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-05-26
            相关资源
            最近更新 更多