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

标签 string haskell io

假设我有一个文件

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    

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

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

这是我目前拥有的:

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()

最佳答案

您的代码暗示了一些对 Haskell 的误解,所以在找到解决方案之前让我们仔细检查一下您的代码。

import Data.Text as T

您正在使用 Text,太棒了!我建议您还使用读写 Text 类型的 IO 操作,而不是使用在 String(字符链接列表)上工作的 prelude 提供的操作。即,将 Data.Text.IO 导入为 T

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

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

main :: IO ()
main = do
    file <- readTheFile
    file2 <- (T.strip file)
    return()

这里有两个问题。

问题一 请注意,您在这里使用了 strip 就好像它是一个 IO 操作...但它不是。我建议您了解更多关于 IO 和绑定(bind)(do 表示法)与 let 绑定(bind)变量的信息。 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)

关于string - Haskell 从文件中删除尾随和前导空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43095903/

相关文章:

php - 在 PHP 中测试 UTF-8 字符串是一种可靠的方法吗?

c++ - 这两种寻址方式有什么区别

haskell - 确定执行脚本的名称

python - 使用windows用python打开word文档

string - 在 Fortran 中按名称获取文件单元,反之亦然

java - 如何关闭Java Input Streams?

c - 字符数组的文字字符串初始值设定项

haskell - 如何查找文件夹的所有子文件夹?

haskell - 无限列表的列表理解

java - 在 Java 字符串中搜索和替换格式化属性