【问题标题】:Remove characters from String in Haskell从 Haskell 中的字符串中删除字符
【发布时间】:2015-05-15 00:44:00
【问题描述】:

我正在创建一个程序,它可以读取文本文件并拆分单词并将它们存储在列表中。我一直在尝试创建一个函数,该函数接受一个字符串,该字符串是文件中的整个文本字符串并删除标点符号,例如“;”、“”、“。”但不幸的是还没有任何运气。该程序可以在没有标点符号功能的情况下运行,但是当我将其包含到(toWords fileContents) 时就不行了 请有人看看我做了什么,看看我做错了什么。

这是我目前的代码:

main = do  
       contents <- readFile "LargeTextFile.txt"
       let lowContents = map toLower contents
       let outStr = countWords (lowContents)
       let finalStr = sortOccurrences (outStr)
       let reversedStr = reverse finalStr
       putStrLn "Word | Occurrence "
       mapM_ (printList) reversedStr

-- Counts all the words.
countWords :: String -> [(String, Int)]
countWords fileContents = countOccurrences (toWords (removePunc fileContents))

-- Splits words and removes linking words.
toWords :: String -> [String]
toWords s = filter (\w -> w `notElem` ["an","the","for"]) (words s)

-- Remove punctuation from text String.
removePunc :: String -> String
removePunc xs = x | x <- xs, not (x `elem` ",.?!-:;\"\'")

-- Counts, how often each string in the given list appears.
countOccurrences :: [String] -> [(String, Int)]
countOccurrences xs = map (\xs -> (head xs, length xs)) . group . sort $ xs

-- Sort list in order of occurrences.
sortOccurrences :: [(String, Int)] -> [(String, Int)]
sortOccurrences sort = sortBy (comparing snd) sort

-- Prints the list in a format.
printList a = putStrLn((fst a) ++ " | " ++ (show $ snd a))

【问题讨论】:

    标签: haskell


    【解决方案1】:

    你可能想要:

    removePunc xs = [ x | x <- xs, not (x `elem` ",.?!-:;\"\'") ]
    

    带括号。

    【讨论】:

    • 另一种选择是只使用filter (not . (`elem` ",.?!-:;\"\'")) xs
    • 成功了,谢谢!我只是错过了方括号。
    • 另一种选择是修改@bheklilr 的答案:filter (`notElem` ",.?!-:;\"\'") xs
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-10
    • 2016-07-26
    相关资源
    最近更新 更多