I have this code example where I'm reading from a text file four different colors.
This is my colors.txt :
###
#####
#########
#example colors
#line of colors
#line colors PART 1
color gray
color blue
# line colors PART 2
color yellow
color green
Where's I'm getting gray
and blue
from PART 1
, and yellow
and blue
from PART 2
My Python code for this example is:
#!/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(part_index):
color = re.findall('color\s(.*?)\s',dic[part_index] )
return color
print color(1) #Colors of PART 1
print color(2)# Colors of PART 2
After runing this code I got this output:
Part 1 : ['gray', 'blue']
Part 2 : ['yellow', 'green']
I would like to print the colors by separated for example
color(1)
as gray
, color(2)
as blue
, color(3)
as yellow
and color(4)
as green
That way my output would be:
gray
blue
yellow
green
Is there a possible way to do that? if so I'd be very grateful. Thank you Community.
You can create this list, and then use it in color
instead of dic
.
colors = [None] # Garbage value to preserve 1-based indexing
for value in dic.values():
colors += value
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.