我开始学习Elixir,这也是我的第一个动态语言,所以我真的失去了没有类型声明的函数.
我想做什么:def create_training_data(file_path, indices_path, result_path) do
file_path
|> File.stream!
|> Stream.with_index
|> filter_data_with_indices(indices_path)
|> create_output_file(result_path)
end
def filter_data_with_indices(raw_data, indices_path) do
Stream.filter raw_data, fn {_elem, index} ->
index_match?(index, indices_path)
end
end
defp index_match?(index, indices_path) do
indices_path
|> File.stream!
|> Enum.any? fn elem ->
(elem
|> String.replace(~r/\n/, "")
|> String.to_integer
|> (&(&1 == index)).())
end
end
defp create_output_file(data, path) do
File.write(path, data)
end
Run Code Online (Sandbox Code Playgroud)
当我调用该函数时:
create_training_data("./resources/data/usps.csv","./resources/indices/17.csv","./output.txt")
Run Code Online (Sandbox Code Playgroud)
它返回{:error,:badarg}.我已经检查过,错误发生在create_output_file函数上.
如果我注释掉函数create_output_file,我得到的是一个流(有点意义).问题可能是我不能给Stream to File.write吗?如果是问题,我该怎么办?我在文档上没有找到任何相关内容.
所以,问题是File.write的路径应该没问题,我修改了这个函数:
defp create_output_file(data, path) do
IO.puts("You are trying to write to: " <> path)
File.write(path, data)
end
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试使用这些参数运行时:
iex(3)> IaBay.DataHandling.create_training_data("/home/lhahn/data/usps.csv", "/home/lhahn/indices/17.csv", "/home/lhahn/output.txt")
You are trying to write to: /home/lhahn/output.txt
{:error, :badarg}
iex(4)> File.write("/home/lhahn/output.txt", "Hello, World")
:ok
Run Code Online (Sandbox Code Playgroud)
所以,我仍然有:badarg问题,也许我传递的内容不对?
第一件事:将元组输入 write 中。您必须首先从它们中提取数据:
file_path
|> File.stream!
|> Stream.with_index
|> filter_data_with_indices(indices_path)
|> Stream.map(fn {x,y} -> x end) # <------------------ here
|> create_output_file(result_path)
Run Code Online (Sandbox Code Playgroud)
第二件事:
看起来您无法将 Stream 馈送到 File.write/2 中,因为它需要 iodata。如果在写入之前将流转换为列表,一切都会顺利:
defp create_output_file(data, path) do
data = Enum.to_list(data)
:ok = File.write(path, data)
end
Run Code Online (Sandbox Code Playgroud)