【问题标题】:Combining list comprehension and pipe operator结合列表理解和管道运算符
【发布时间】:2021-09-18 06:39:32
【问题描述】:

我有一个这样的引号列表:

[

{"March 28, 2021", "It only took one call for him to help me into a brand new 2021 it was so AMAZINGLY GOOD IM STILL HAPPY love it"},
{"March 28, 2021", "We had been looking for a 2021 Suburban for about 6 months and no one could find exactly what we wanted! We contacted Adrian at McKaig and he told us he could order one for us! Our Suburban was delivered in 4 weeks and had everything on it that we wanted! Adrian, Brandon, Dennis and Freddie all worked with us to get exactly what we wanted! They made phone calls and deals for us right on the spot and we drove out with a beautiful black Suburban! We will definitely use Adrian and McKaig Chevrolet again! Thank you for a fun car buying experience!"},
...
        ]

我一直在尝试让这个函数遍历列表中的每个引号,以计算每个引号中的单词数,然后返回原始列表以及映射到每个引号的数字。我被卡住了,现在不知道要寻找什么。如果有人能引导我朝着正确的方向前进,我将不胜感激。

代码如下:

def count(q) do
  q
  |> String.downcase()
  |> String.replace(~r/@|#|\$|%|&|\^|:|_|!|,/u, " ") 
  |> String.split()
  |> Enum.count()
end

def count_added() do
  items = get_body() #the list of quotes
  Enum.each(items, &count/1)
  for x <- items do 
    Map.put_new_lazy(items, "count", &count/1)
  end
end

【问题讨论】:

  • 简单地调用Enum.each(items, &amp;count/1) 不会更新items,因为它是不变的。如果您希望items 成为上述调用的结果,您需要重新分配它

标签: elixir list-comprehension


【解决方案1】:

首先没有Map,所以调用Map.put_new_lazy/3无论如何都不会成功。

此外,在计算单词之前将字符串小写是有意义的。你真正想要的,是用String.split/3 分割一个或多个非字母数字符号。

input = [
  {"March 28, 2021", "It only took"},
  {"March 28, 2021", "We had been looking for a 2021 Suburban!"}
]

for {title, x} <- input do
  %{title: title,
    text: x,
    count: x |> String.split(~r/[^\p{L}\d]+/u, trim: true) |> Enum.count()
  }
end
#⇒ [
#   %{count: 3, text: "It only took", title: "March 28, 2021"},
#   %{
#     count: 8,
#     text: "We had been looking for a 2021 Suburban!",
#     title: "March 28, 2021"
#   } 
# ]

【讨论】:

  • 非常感谢@Aleksei Matiushkin!最后一个澄清问题。在这种情况下,您是如何获得 text 键中的值来消除 title 或日期的?
  • 我不明白这个问题,对不起。在理解中,我对输入进行模式匹配,以便 title 成为元组的第一个元素,x 成为第二个元素。地图是手工制作的。
  • 哦,对不起,我明白你现在在做什么。非常感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2021-09-03
  • 2019-07-15
  • 2022-12-05
  • 1970-01-01
  • 2019-04-05
  • 2018-11-28
  • 2012-10-13
  • 1970-01-01
相关资源
最近更新 更多