结合列表理解和管道运算符

问题描述

我有一个这样的报价列表:

[

{"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,"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

解决方法

首先没有 Map,因此在任何情况下调用 Map.put_new_lazy/3 都不会成功。

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

input = [
  {"March 28,2021","It only took"},{"March 28,"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"
#   } 
# ]

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...