【发布时间】:2021-04-21 20:33:05
【问题描述】:
目标是一个脚本,它逐行读取文件,包含文件路径(Windows 和 Linux)。它剥离路径,只留下带有扩展名的文件名。然后用“_”替换文件名中的任何特殊字符 - 下划线,最后将连续的下划线减少一个。 就像 st__a___ck 变成 st_a_ck。 我让它工作了,但我相信可能有更好/更好看的方式来做到这一点。 我是一个非常初学者,仍在学习以 Elixir/功能方式思考。 我想要的是看到不同的方法来做这件事,改进和提炼一点的方法。
测试样本:
c:\program files\mydir\mydir2\my&@Doc.doc
c:\program files\mydir\mydir2\myD$oc2.doc\
c:\\program files\\mydir\\mydir2\\myD;'oc2.doc
c:\\program files\\mydir\mydir2\\my[Doc2.doc\\
/home/python/projects/files.py
/home/python/projects/files.py/
//home//python//projects//files.py
//home//python//projects//files.py//
c:\program files\mydir\mydir2\my!D#oc.doc
c:\program files\mydir\mydir2\myDoc2.doc\
c:\\program files\\mydir\\mydir2\\my';Doc2.doc
c:\\program files\\mydir\mydir2\\myD&$%oc2.doc\\
/home/python/projects/f_)*iles.py
/home/python/projects/files.py/
//home//python//projects//fi=-les.py
//home//python//projects//fil !%es.py//
/home/python/projects/f_)* iles.py
/home/python/projects/fi les.py/
//home//python//projects//fii___kiii=- les.py
//home//python//projects//ff###f!%#illfffl! %es.py//
代码:
defmodule Paths do
def read_file(filename) do
File.stream!(filename)
|> Enum.map( &(String.replace(&1,"\\","/")) )
|> Enum.map( &(String.trim(&1,"\n")) )
|> Enum.map( &(String.trim(&1,"/")) )
|> Enum.map( &(String.split(&1,"/")) )
|> Enum.map( &(List.last(&1)) )
|> Enum.map( &(String.split(&1,".")) )
|> Enum.map( &(remove_special)/1 )
|> Enum.map( &(print_name_and_suffix)/1 )
end
defp print_name_and_suffix(str) do
[h|t] = str
IO.puts "Name: #{h}\t suffix: #{t}\t: #{h}.#{t}"
end
defp remove_special(str) do
[h|t] = str
h = String.replace(h, ~r/[\W]/, "_")
h = String.replace(h, ~r/_+/, "_")
[h]++t
end
end
Paths.read_file("test.txt")
非常感谢任何见解。
编辑: 我稍微重构了代码。哪个版本更像 Elixir 风格?
defmodule Paths do
def read_file(filename) do
File.stream!(filename)
|> Enum.map( &(format_path)/1 )
|> Enum.map( &(remove_special)/1 )
|> Enum.map( &(print_name_and_suffix)/1 )
end
defp format_path(path) do
path
|> String.replace("\\","/")
|> String.trim("\n")
|> String.trim("/")
|> String.trim("\\")
end
defp print_name_and_suffix(str) do
[h|t] = str
IO.puts "Name: #{h}\t suffix: #{t}\t: #{h}#{t}"
end
defp remove_special(str) do
ext = Path.extname(str)
filename = Path.basename(str)
|> String.trim(ext)
|> String.replace(~r/[\W]/, "_")
|> String.replace( ~r/_+/, "_")
[filename]++ext
end
end
Paths.read_file("test.txt")
【问题讨论】:
-
我认为这是题外话,应该继续codereview.stackexchange.com