Ich habe dieses Codebeispiel, wo ich aus einer Textdatei vier verschiedene Farben lesen.Python Regular Expression Abfrage
Das ist mein colors.txt:
###
#####
#########
#example colors
#line of colors
#line colors PART 1
color gray
color blue
# line colors PART 2
color yellow
color green
Wo die ich gray
und blue
von PART 1
bekommen, und yellow
und blue
von PART 2
Mein Python-Code für dieses Beispiel ist:
#!/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
Nach diesem Code runing habe ich diese Ausgabe:
Teil 1: [ 'grau', 'blau']
Teil 2: [ 'gelb', 'grün']
ich mag die Farben drucken, indem
zum Beispiel getrenntcolor(1)
als gray
, color(2)
als blue
, color(3)
als yellow
und color(4)
als green
Auf diese Weise würde mein ausgegeben:
grau
blau
gelb
grün
Gibt es eine Möglichkeit, das zu tun? Wenn es so wäre, wäre ich sehr dankbar. Danke Community.
Wenn die Ausgabe nicht in mehreren Teilen erfolgen soll, teilen Sie 'content' nicht in mehrere Teile auf. – Kevin