mag*_*tar 3 file-io text-processing haskell 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
Run Code Online (Sandbox Code Playgroud)
但我现在正在学习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....
Run Code Online (Sandbox Code Playgroud)
......而且,我不知道从那里去哪里.
Haskell中最简单的方法涉及在输入上映射Char -> Char替换函数(f下面),生成一个新输出(该interact函数负责fopen/fclose模式):
main = interact $ map f
where
f '\n' = ' '
f '\r' = ' '
f 'é' = 'e'
f '\xa0' = ' '
f c = c
Run Code Online (Sandbox Code Playgroud)
你可以修改它来做你自己的IO,使用Text包等,但字符转换的基本模式是相同的.