Haskell从文件中删除尾随和前导空格

gol*_*m75 2 string io haskell

假设我有一个文件

mary had a little lamb
         It's fleece was white as snow    
Everywhere   
    the child went   
   The lamb, the lamb was sure to go, yeah    
Run Code Online (Sandbox Code Playgroud)

我如何将该文件作为字符串读取,并删除尾随和前导空格?它可以是空格或制表符.删除空格后会打印出这样的内容:

mary had a little lamb
It's fleece was white as snow
Everywhere
the child went
The lamb, the lamb was sure to go, yeah
Run Code Online (Sandbox Code Playgroud)

这是我目前的情况:

import Data.Text as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()
Run Code Online (Sandbox Code Playgroud)

Tho*_*son 5

您的代码提示了一些关于Haskell的误解,所以让我们在获得解决方案之前完成您的代码.

import Data.Text as T
Run Code Online (Sandbox Code Playgroud)

你正在使用Text,太棒了!我建议你也使用读写Text类型的IO操作,而不是在Strings(链接字符列表)上工作的前奏提供的操作.那是,import Data.Text.IO as T

readTheFile = do
    handle <- openFile "mary.txt" ReadMode
    contents <- hGetContents handle
    putStrLn contents
    hClose handle
    return(contents)
Run Code Online (Sandbox Code Playgroud)

哦,嘿,使用hGetContents和手动打开和关闭文件可能容易出错.考虑readTheFile = T.readFile "mary.txt".

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()
Run Code Online (Sandbox Code Playgroud)

这里有两个问题.

发布一个通知,你已经使用strip过,好像它是一个IO动作......但事实并非如此.我建议你学习更多关于IO和绑定(do notation)vs let-bound变量的知识. strip计算一个新的类型值,Text并且可能你想用这个值做一些有用的东西,比如写它.

问题二剥离整个文件不同于一次剥离每一行.我建议你阅读mathk的答案.

所以最后我想你想要:

-- Qualified imports are accessed via `T.someSymbol`
import qualified Data.Text.IO as T
import qualified Data.Text as T

-- Not really need as a separate function unless you want to also
-- put the stripping here too.
readTheFile :: IO T.Text
readTheFile = T.readFile "mary.txt"

-- First read, then strip each line, then write a new file.
main :: IO ()
main =
    do file <- readTheFile
       let strippedFile = T.unlines $ map T.strip $ T.lines file
       T.writeFile "newfile.txt" (T.strip strippedFile)
Run Code Online (Sandbox Code Playgroud)