0

I have an app in python where I'm reading from a plain text.

It's working fine. My question is there is a possible way to read from multiple lines instead of line by line. For example here's is my plain text file color.txt:

###
#####
#########

#example colors
#line of colors
#line colors PART 1
        color1 gray
        color2 blue


# line colors PART 2
iface eth1 inet static
        color1 yellow
        color2 green

I want color1 and color2 from "part1" so I'm reading this line by line but if I change position of color1 for color2 I'm getting an error, so is there a way to read everything inside of "part1" ? that way I can get the same result.

Here's my full code:

from flask import Flask,render_template,flash,request,redirect
import os
import sys
app = Flask(__name__)

def color1_p1():
    with open('color.txt', 'r+') as f:
        for i, line in enumerate(f):
          if i == 7: 
            found_color = line.find('color1')
            if found_color != -1:
               color = line[found_color+len('color1:'):]
               print ('Color: '), color
    return color


def color2_p1():
    with open('color.txt', 'r+') as f:
        for i, line in enumerate(f):
          if i == 8: 
            found_color = line.find('color2')
            if found_color != -1:
               color = line[found_color+len('color2:'):]
               print ('Color: '), color
    return color


def color1_p2():
    with open('color.txt', 'r+') as f:
        for i, line in enumerate(f):
          if i == 13: 
            found_color = line.find('color1')
            if found_color != -1:
               color = line[found_color+len('color1:'):]
               print ('Color: '), color
    return color

def color2_p2():
    with open('color.txt', 'r+') as f:
        for i, line in enumerate(f):
          if i == 14: 
            found_color = line.find('color2')
            if found_color != -1:
               color = line[found_color+len('color2:'):]
               print ('Color: '), color
    return color



@app.route('/')
def showLine():
    color1 = color1_p1()
    color2 = color2_p1()
    color3 =color1_p2()
    color4 = color2_p2()
    return render_template('color.html', color1=color1, color2=color2, color3=color3,color4=color4)

if __name__ == '__main__':
    app.run(debug=True)

as you can see I'm getting the content by lines, I want to read everything inside of part "1" , I tried without the lines but when doing so it will read the "part 2" or the first "color1 and color2" they find.

Here's my output:

Click here!

All I want is to read color1 or color2 no matter the line it is, if I change the position the program should read this, and same should happen in part 2.

3
  • You might be able to use a regular expression to find the "pattern" of color1 Commented Nov 9, 2016 at 4:23
  • how do you suggest to do that? Commented Nov 9, 2016 at 6:10
  • I don't think it would be any better than what you've done Commented Nov 9, 2016 at 6:12

1 Answer 1

2
#!/usr/lib/env python
import re

file = open("color.txt","r")
content = file.read()
file.close()
content = content.split('PART ')[1:]
dic = {}
for part in content:
    dic[int(part[0])] = part[1:]

def color(color_index, part_index):
    color = re.search('color{_color_index}\s(.*?)\s'.format(_color_index=color_index),dic[part_index]).group(1)
    print 'color',color_index,'of PART',part_index,":",color
    return color

color(1,1)#color 1 of PART 1 : gray
color(2,1)#color 2 of PART 1 : blue
color(1,2)#color 1 of PART 2 : yellow
color(2,2)#color 2 of PART 2 : green

This way, you can get what you want no matter how parts and colors are arranged.

Sign up to request clarification or add additional context in comments.

6 Comments

Is there a possible way to make it work without the index 1 or 2? for example with only the word "color" in my plain text? @Max
You can get all colors appeared in your text by colors = re.findall('color\d\s(.*?)\s',open('color.txt','r').read()) if you don't care the index of colors and parts. Or by colors = re.findall('color\d\s(.*?)\s',dic[part_index]) if you want them found corresponding to parts. And I think you'd better learn some fundamental knowledge on regular expression, which helps a lot when you wanna find specific string in a text file.
I tried color = re.findall('color\d\s(.*?)\s',dic[part_index]) because I want them by parts and I got the following result by console [ ] which should be red instead? @Max
I test it with color.txt you provided above, and get ['gray', 'blue'] and ['yellow', 'green'] as results of color(1) and color(2) respectively. So I think the format of you current text file may be different from the one you provided above? Coz the regex 'color\d\s(.*?)\s' find strings organized exactly like color\d\sred\s, where \d represents a digit, \s represents a whitespace character. So if your text format changes, make sure you write proper regular expression to match them. Here is a link to document of re lib [docs.python.org/2/library/re.html] @pythonbegineer
Thanks for you answer! yes I have the same result as you have, but I meant I got ['gray' , 'blue'] and ['yellow', 'green'] as results of color(1) and color(2). But in the first answer you I got the four colors in four results as color(1), color(2),color(3) and finally color(4). I would like to have something like that. for example instead of print color(1) and get ['gray' , 'blue'] I would like to print color(1) and get 'gray' after that color(2) and get 'blue'. That's all I need. Is that possible? . By the way the link didn't work. Thanks..! @Max
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.