朱莉娅的月份名称值?

时间:2018-06-07 12:10:26

标签: julia

我需要将特殊格式的文本日期转换为Julia中的日期。我在Dates documentation找到了MONTHTOVALUE字典,但Dates命名空间中缺少此对象,在帮助中没有给出结果,只出现在Github source code in the documentation中。我使用Date.format()格式"U"来定义我自己的MONTHTOVALUE

  # Build dictionary from month names to integers
  MONTHTOVALUE = Dict{String, Integer}()
  for i in 1:12
      month = Dates.format(Date(1990, i, 1), "U")
      MONTHTOVALUE[month] = i
  end;

  # Regular expression for date in the format [Month Year(Quarter)]
  date_regex = r"(^[A-Z][a-z]*) ?(\d{4}) ?\((I*V?)\)";
  function string_to_date(date_string)
      month = MONTHTOVALUE[replace(date_string, date_regex, s"\1")]
      year = parse(Int, replace(date_string, date_regex, s"\2"))
      return Dates.Date(year, month, 1)
  end;
  @assert Dates.Date(1860, 10, 1) == string_to_date("October 1860(III)")

MONTHTOVALUE字典是否已经存在,或者您是否建议使用更简洁的字典?

2 个答案:

答案 0 :(得分:1)

如果我正确理解了这个问题,您希望访问Dates模块中的字典,该字典将月份名称映射到其编号(“March”=> 3等),这是正确的吗?

如果是这样,Dates.LOCALES["english"].month_value似乎是您正在寻找的那个:

julia> Dates.LOCALES["english"].month_value
Dict{String,Int64} with 24 entries:
  "January"   => 1
  "august"    => 8
  "May"       => 5
  "may"       => 5
  "December"  => 12
  "january"   => 1
  "August"    => 8
  "november"  => 11
  "december"  => 12
  "September" => 9
  "july"      => 7
  "september" => 9
  "October"   => 10
  "june"      => 6
  "November"  => 11
  "April"     => 4
  "February"  => 2
  "october"   => 10
  "March"     => 3
  "June"      => 6
  "april"     => 4
  "march"     => 3
  "february"  => 2
  "July"      => 7

(如果需要,还有一个Dates.LOCALES["english"].month_abbr_value。)

我猜这部分文档已经过时,MONTHTOVALUE曾经是month_value dict的旧名称。

还有函数Dates.monthname_to_value,像Dates.monthname_to_value("September",Dates.LOCALES["english"])一样使用,为上面的dict提供了一个接口。

答案 1 :(得分:0)

我没有听说过朱莉娅,但是段落似乎很重要:

  

u也支持文本形式的月份解析   和U字符,缩写和全长月份​​名称,   分别。默认情况下,只支持英文月份名称,所以你   对应于" Jan"," Feb"," Mar"等等。对应于   " 1月"," 2月"," 3月"等。与其他name =>值类似   映射函数dayname()和monthname(),自定义语言环境可以   通过传入locale => Dict {String,Int}映射到   MONTHTOVALUEABBR和MONTHTOVALUE用于缩写和全名   月份名称。

https://docs.julialang.org/en/v0.6.2/manual/dates/

编辑:我认为你可以像这样制作字典:

monthtovalue = Dict{UTF8String, Int}()
for (value, name) in VALUETOMONTH[locale::AbstractString="english"]
    monthtovalue[lowercase(name)] = value
end
相关问题