Skip to content Skip to sidebar Skip to footer

Python Regex To Parse Text File, Get The Items In List And Count The List

I have a text file which contains some data. I m particularly interested in finding the count of the number of items in v_dims v_dims pattern in my text file looks like this : v_di

Solution 1:

This answers your question of how to do it with regular expression matching. However, as Mark indicated, there may be a smarter method.

>>> import re
>>> f = open("/tmp/a")
>>> lines = f.readlines()
>>> f.close()
>>> items = []
>>> for line in lines:
...     m = re.search("\"(.+)\",$", line)
... if m:
...             items.append(m.group(1))
>>> items
['Sales', 'Product Family', 'Sales Organization', 'Region', 'Sales Area', 'Sales office', 'Sales Division', 'Sales Person', 'Sales Channel', 'Sales Order Type', 'Sales Number', 'Sales Person', 'Sales Quantity']

Solution 2:

  • Here we find v_dims element from text file.
    • Remove the whitespaces from data.
    • Convert data in list.
    • Calculate length of list.

import re
withopen(fname, "r") as fp: 
    data = fp.read()
rx_blanks=re.compile(r"\s+")
v_dims_list = eval("["+rx_blanks.sub("",data[re.search(r'v_dims={',data).end():][:re.search(r'},',data[re.search(r'v_dims={',data).end():]).start()])+']')
or
v_dims_list = list(eval(rx_blanks.sub('',data[re.search(r'v_dims={',data).end():][:re.search(r'},',data[re.search(r'v_dims={',data).end():]).start()])))

if you want length

len(v_dims_list)

Post a Comment for "Python Regex To Parse Text File, Get The Items In List And Count The List"