0

I have text file which is made up with several sections. Sections always started with non-space. And sub-section always started with space. Based on input.txt, following is my expected result. in this example i am trying to search for “101” and if 101 appears either in section or subsection. i want to display section with subsection. i am trying to parse the section and store in dynamic variable. But i am not sure how to store section dynamically in a variable.

Input.txt

test1 text101
  aaa
  bbb
  ccc

test2 text101
  aaa
  bbb
  ccc
  ddd 101

test3 text101 - 123

test4 text123
  aaa
  bbb
  ccc
  ddd 101

test5 text456
  aaa
  bbb
  ccc

test6 101
  qqq
  ppp

test7 text101 - 123
test8 text102 - 123
Test9 text101 - 123
Test10 text102 - 123

Python 3.0 code:

find_txt = '101'
result = []
f = open(r'\\input.txt')
for line in f:
    if (line[:1]!=' '):
        result.append(line)

print ('Result:')
for element in result:
    if find_txt in element:
        print (element, end='')

Output:

test1 text101
  aaa
  bbb
  ccc

test2 text101
  aaa
  bbb
  ccc
  ddd 101

test3 text101 - 123

test4 text123
  aaa
  bbb
  ccc
  ddd 101

test6 101
  qqq
  ppp

test7 text101 - 123

Test9 text101 - 123
user1582596
  • 503
  • 2
  • 5
  • 16

1 Answers1

1

I'd suggest something else which is IMHO more pythonic solution to the problem: Divide the file into sections and filter out unwanted content. The algorithm is something like this:

  1. Read the whole file (with read function) to a variable (let's say content). It will be a string variable. Refer: Doc
  2. Split the string with the appropriate regex (divided by no-white space starting lines) into sections including the subsections. Refer: How to use regex to split string. You'll have a list of strings.
  3. Use list comprehension to filter out unwanted content. You'll have a list. Example: Here
  4. Concatenate the list with new line character using join string function. Example: Here

Good luck.

ps. I can provide the code, but you may want to wrestle with it first :)

CM.
  • 1,007
  • 1
  • 7
  • 19