- Haskell Data Analysis Cookbook
- Nishant Shukla
- 250字
- 2021-12-08 12:43:39
Splitting a string on lines, words, or arbitrary tokens
Useful data is often interspersed between delimiters, such as commas or spaces, making string splitting vital for most data analysis tasks.
Getting ready
Create an input.txt
file similar to the following one:
$ cat input.txt first line second line words are split by space comma,separated,values or any delimiter you want
Install the split
package using Cabal as follows:
$ cabal install split
How to do it...
- The only function we will need is
splitOn
, which is imported as follows:import Data.List.Split (splitOn)
- First we split the string into lines, as shown in the following code snippet:
main = do input <- readFile "input.txt" let ls = lines input print $ ls
- The lines are printed in a list as follows:
[ "first line","second line" , "words are split by space" , "comma,separated,values" , "or any delimiter you want"]
- Next, we separate a string on spaces as follows:
let ws = words $ ls !! 2 print ws
- The words are printed in a list as follows:
["words","are","split","by","space"]
- Next, we show how to split a string on an arbitrary value using the following lines of code:
let cs = splitOn "," $ ls !! 3 print cs
- The values are split on the commas as follows:
["comma","separated","values"]
- Finally, we show splitting on multiple letters as shown in the following code snippet:
let ds = splitOn "an" $ ls !! 4 print ds
- The output is as follows:
["or any d","limit","r you want"]
推薦閱讀
- SoapUI Cookbook
- Instant Apache Stanbol
- Django Design Patterns and Best Practices
- JSP開(kāi)發(fā)案例教程
- Learning JavaScript Data Structures and Algorithms
- Keras深度學(xué)習(xí)實(shí)戰(zhàn)
- Learning R for Geospatial Analysis
- 零基礎(chǔ)學(xué)C語(yǔ)言第2版
- Orleans:構(gòu)建高性能分布式Actor服務(wù)
- 從Power BI到Analysis Services:企業(yè)級(jí)數(shù)據(jù)分析實(shí)戰(zhàn)
- C語(yǔ)言程序設(shè)計(jì)教程
- FusionCharts Beginner’s Guide:The Official Guide for FusionCharts Suite
- Getting Started with RethinkDB
- 走近SDN/NFV
- Mastering MeteorJS Application Development