Created
September 5, 2012 20:07
-
-
Save squarepegsys/3643738 to your computer and use it in GitHub Desktop.
A parser in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This is a version of a parser I wrote in Python for | |
www.powerhousetoolparts.com. After reading about Case Classes and Pattern Matching, | |
I was wondering how nice it would be in Scala. And, while I don't | |
cover all the edge cases, it's nice indeed. | |
The file has records like: | |
FLE100102 WRENCH 14MM EACH(ACTIVE)S2650FLEX PARTS 5.830 5.830FLEX 76.00 | |
FLE100110 SPANNER WRENCH EACH(ACTIVE)S2650FLEX PARTS 5.500 5.500FLEX 7.00 | |
FLE100277 SEAL EACH(ACTIVE)S2650FLEX PARTS 2.650 2.650FLEX 3.00 | |
*/ | |
case class Part(vendor: String ,part_num: String , name: String, price: String) | |
val VendorRegExp = """^([A-Z]{2,3})(.+)$""".r | |
def find_vendor_part(expr: String) = expr match { | |
case (VendorRegExp(vendor,part_num))=>List(vendor,part_num) | |
case _ => Nil | |
} | |
def parser(line: String) : Part ={ | |
val results = line.split(" ").map(_.trim).filter(_ != "") | |
val front_stuff = find_vendor_part(results(0)) | |
Part(front_stuff(0),front_stuff(1),results(1),results.last) | |
} | |
val parts = scala.io.Source.fromFile("parts.txt").getLines().map(parser(_)) | |
parts.foreach{ part=> | |
println(part) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment