- 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"]
推薦閱讀
- What's New in TensorFlow 2.0
- Learning AWS Lumberyard Game Development
- Scratch 3.0少兒編程與邏輯思維訓(xùn)練
- Java EE 7 Performance Tuning and Optimization
- 自制編程語言
- AppInventor實(shí)踐教程:Android智能應(yīng)用開發(fā)前傳
- HTML5與CSS3基礎(chǔ)教程(第8版)
- Java Fundamentals
- Domain-Driven Design in PHP
- 新印象:解構(gòu)UI界面設(shè)計
- Hacking Android
- Advanced Python Programming
- 大學(xué)計算機(jī)基礎(chǔ)實(shí)訓(xùn)教程
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- Go Systems Programming