[英]Filtering String from List Haskell
我正在尝试编写一个程序,该程序读取文本文件,然后显示文件中单词的频率和计数。 接下来,我需要从文本文件中过滤某些单词。 我一直在寻找在线资源两个小时,但仍然找不到我想要的!
到目前为止,我已经为程序提供了代码:
lowercase = map toLower
top doc = wordPairs
where
listOfWords = words (lowercase doc)
wordGroups = group (sort listOfWords)
wordPairs = reverse
$ sort
$ map (\x -> (length x, head x))
$ filterWords
wordGroups
filterWords :: String -> String
filterWords = filter (all (`elem` ["poultry outwits ants"])) . words
如果以其他方式拆分程序,可能会更容易。 例如
import Data.List(group,sort)
import Control.Arrow((&&&))
freq :: Ord a => [a] -> [(Int,a)]
freq = reverse . sort . map (length &&& head) . group . sort
第二部分将定义此函数的输入。 您只想过滤某些元素。
select :: Eq a => [a] -> [a] -> [a]
select list = filter (`elem` list)
因为您不需要特定的类型输入,所以这些将使测试更加容易。
最后,您可以将它们绑在一起
freq $ select ["a","b","c"] $ words "a b a d e a b b b c d e c"
会给你
[(4,"b"),(3,"a"),(2,"c")]
有我的代码可以解决您的问题
top :: String -> [(Int,String)] --Signature is always important
top = sorter . wordFrequency . groups . filtered --just compose `where` functions
where
-- This will filter your words
filtered = filter (`notElem` ["poultry","outwits","ants"]) . words . map toLower
-- Group your words
groups = group . sort
-- Create the pairs of (count, word)
wordFrequency = map (length &&& head)
-- Sort your list by first. for reverse just switch a and b
sorter = sortBy (\ a b -> fst b `compare` fst a)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.