微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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

[

{"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"
#   } 
# ]

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?