Search code examples
pythonlisttexttext-extraction

How to xtract multiple numbers delimited by brackets from a txt document into a python list?


So I have a .txt file which looks like the following:

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

What I need to do is to extract all the numbers in between the brackets [] and append them in a list which I will then use for further analysis. The final result should then be:

list = [1227194,1227195,1227196]

What would be the most pythonic way to achieve this?


Solution

  • try this:

    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
    

    output:

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