Haskell上的过滤字符

Haskell上的过滤字符,haskell,Haskell,我读了一个文件的内容,但为了处理它们,我需要过滤3个我不需要的字符 我读了一篇文章,其中有人=;,和其他不需要的角色,所以我尝试了一些类似的东西,但我无法让它工作: --test filtering ::= getLines = liftM lines . readFile main :: IO () main = do putStrLn "Enter a text file: " filename <- getLine --test filt

我读了一个文件的内容,但为了处理它们,我需要过滤3个我不需要的字符

我读了一篇文章,其中有人=;,和其他不需要的角色,所以我尝试了一些类似的东西,但我无法让它工作:

--test filtering ::=
getLines = liftM lines . readFile

main :: IO ()
main = do
    putStrLn "Enter a text file: "
    filename <- getLine
    --test filter ::=
    list <- filtering filename
    
    filtering :: String -> [String]
    filtering = folder clean . lines
        where clean = filter (not . flip any ["=", ":"] . (==) . take 1) 

    {-
    --this gets all the lines of the file and get it on a List, nut ::= is on the List too
    list <- getLines filename
    -}

每一行的内容都是这样的:word::=word,我想过滤的字符是::=,这样我就可以得到这些单词了


有什么方法可以在一行中执行,还是必须在do块中逐行读取?

让我们定义一个函数,该函数以文件路径为参数,读取关联的文件readFile,将其内容拆分为行,然后,通过将每个行映射分解为单词来处理它,只保留不等于::=/=:::=,并返回剩余单词列表的结果列表。直截了当地说:

filtering :: FilePath -> IO [[String]]
filtering fp = readFile fp >>= return . map go . lines
  where go line = [ w | w <- words line, w /= "::=" ]
然后:

请注意,在这里,我们使用列表理解来表示过滤,但您当然也可以使用显式调用来过滤:

我们在这里假设,通过将行分解为单词来处理它是解决问题的正确粒度。如果需要更精细的粒度,当然也可以将行作为字符列表遍历:

go line = words [ c | c <- line, c `notElem` "::=" ]
这样,您可以逐个字符进行过滤,然后才将行拆分为单词

> filtering "test.txt"
[["one","two","three"],["four","five","six"]]
go = filter (/= "::=") . words
go line = words [ c | c <- line, c `notElem` "::=" ]
go = words . filter (`notElem` "::=")