在Haskell中表达一系列脚本化的Python字符串替换

时间:2012-05-26 22:18:03

标签: haskell file-io text-processing replace

我经常使用Python来替换文本中的各种类型的字符,使用如下所示的脚本:

#!/usr/bin/env python                                                                                                                                                                                                                                                         
# coding=UTF-8

import sys

for file in sys.argv[1:]:                                                                                                                                                                                                                                                     
    f = open(file)                                                                                                                                                                                                                                                            
    fs = f.read()
    r1 = fs.replace('\n',' ')
    r2 = r1.replace('\r',' ')                                                                                                                                                                                                                                                   
    r3 = r2.replace('. ','.\n\n')                                                                                                                                                                                                                                                   
    r4 = r3.replace('é','e')
    r5 = r4.replace('\xc2',' ')
    r6 = r5.replace('\xa0',' ')
    r7 = r6.replace(' ',' ')
    r8 = r7.replace(' ',' ')
    r9 = r8.replace('\n ','\n')
    f.close()                                                                                                                                                                                                                                                                 
    print r8

但我现在正在学习Haskell,因为我厌倦了Python。

我最好尝试在Haskell中这样做

#!/usr/bin/runhaskell 

import System.IO

main :: IO ()
main = do 
       inh <- getArgs >>= withFileLines
       outh <- -- ??
       mainloop inh outh
       hClose inh
       hClose outh

replacements :: String -> String
replacements = unwords $ map -- hmm....

......而且,我不知道该去哪里。

1 个答案:

答案 0 :(得分:5)

Haskell中最简单的方法涉及在输入上映射Char -> Char替换函数(下面的f),生成一个新输出(interact函数负责fopen / fclose图案):

main = interact $ map f
      where
        f '\n'   = ' '
        f '\r'   = ' '
        f 'é'    = 'e'
        f '\xa0' = ' '
        f c      = c

你可以修改它来做你自己的IO,使用Text包等,但字符转换的基本模式是相同的。