我在python中有一个应用程序,我从纯文本中读取。
它工作正常。我的问题是有一种可能的方法从多行而不是逐行读取。例如,这里是我的纯文本文件 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
我想要来自" part1"的color1和color2;所以我一行一行地读这个,但是如果我改变color1的color1的位置我得到一个错误,那么有没有办法读取" part1" ?那样我就能得到相同的结果。
这是我的完整代码:
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)
你可以看到我按行获取内容,我想阅读部分内容" 1" ,我尝试没有线条但是这样做时会读到"第2部分"或者第一个" color1和color2"他们找到了。
这是我的输出:
我想要的只是读取color1或color2,无论它是什么行,如果我改变程序应该读取的位置,第2部分也应如此。
答案 0 :(得分: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
这样,无论零件和颜色如何排列,都可以得到你想要的东西。