简体   繁体   中英

Scala: Read a text file and filter on list of values

I want to read in a text file and filter lines that contain only certain values in a particular column. So "if line 1, column 2 contains "Bob" or "Tom" or "Fred", then return that line. The result would only contain lines where the second element of each line is either Bob, Tom, or Fred.

It thought this would work:

 val trans = io.Source.fromFile(inputFile).getLines.map(x => x.split("\11")).filter(line =>("Bob", "Tom", "Fred").contains.line(2)).toArray

but after looking at it, it doesn't really make sense that it would work (and it doesn;t). I can do it with a single value like this:

val trans = io.Source.fromFile(inputFile).getLines.map(x => x.split("\11")).filter(line =>line(2) contains "Bob").toArray

but can't figure how do multiple values.

Any help is appreciated.

You want to check whether one column of a line—a single string —is contained in a sequence of strings:

val names = Seq("Bob", "Tom", "Fred")

Then your filter call becomes

...filter(line => names.contains(line(2)))

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM