如何以编程方式在Julia中定义字符串标识符中的变量?

时间:2018-01-07 03:12:54

标签: julia metaprogramming

我想将abc.conf文件中的字符串设置为变量的名称,例如ProductNoProdName

这可行吗?

abc.conf

ProductNo=>//ProductNo
ProdName=>//ProdName
ProdClass=>//ProdClass
ProdLimit=>//ProdLimit
ProdProfit=>//ProdProfit
ProdYildType=>//ProdYildType
PrdYildTypeOrder=>//PrdYildTypeOrder
ProdArea=>//ProdArea
szComDat=>//szComDat
ProdSaleDate=>//ProdSaleDate
IsCanBuy=>//IsCanBuy
PurStarAmo=>//PurStarAmo
RowNumber=>//RowNumber

朱莉娅琅:

using LibExpat
using Requests


url = "http://ewealth.abchina.com/app/data/api/DataService/BoeProductV2?i=1&s=1500&o=0&w=%25E5%258F%25AF%25E5%2594%25AE%257C%257C%257C%257C%257C%257C%257C1%257C%257C0%257C%257C0"
xdoc = xp_parse(readstring(get(url)))

function ABC()
    open("abc.conf", "r") do f
        for line in eachline(f)
            xml = split(line, "=>")
            #MethodError: Cannot `convert` an object of type Array{LibExpat.ETree,1} to an object of type SubString{String}
            xml[1] = LibExpat.find(xdoc, xml[2])
            println(ProductNo) 
        end
        close(f)
    end
end

ABC()

1 个答案:

答案 0 :(得分:0)

是的!这在朱莉娅是可行的。它可以这样做,注意不要无声地覆盖标识符:

using LibExpat: ETree, xp_parse
using Requests: get

const xp_find = LibExpat.find


function process_xpdoc_config(prefix::String, config::String, xp_doc::ETree)::Dict{String, Vector{ETree}}
    dict = Dict{String, Vector{ETree}}()

    open(config) do file
        for line in eachline(file)
            if !isempty(line)
                xml = split(line, "=>")

                if length(xml) == 2
                    identifier = Symbol(xml[1])
                    prefixed_identifier = Symbol(uppercase(prefix), '_', identifier)
                    value = xp_find(xp_doc, xml[2])

                    if !isdefined(prefixed_identifier)
                        @eval $prefixed_identifier = $value
                        info("defined $prefixed_identifier")

                    else
                        warn("$prefixed_identifier already defined!")
                    end

                    push!(dict, string(identifier) => value)
                end
            end
        end
    end
    return dict
end
url = "http://ewealth.abchina.com/app/data/api/DataService/BoeProductV2?i=1&s=1500&o=0&w=%25E5%258F%25AF%25E5%2594%25AE%257C%257C%257C%257C%257C%257C%257C1%257C%257C0%257C%257C0"
xp_doc = get(url) |> readstring |> xp_parse
abc_conf = "abc.conf"
prefix = "abc"

@eval

的使用功能
julia> ABC = process_xpdoc_config(prefix, abc_conf, xp_doc)
WARNING: ABC_ProductNo already defined!
INFO: defined ABC_ProdName
INFO: defined ABC_ProdClass
INFO: defined ABC_ProdLimit
INFO: defined ABC_ProdProfit
INFO: defined ABC_ProdYildType
INFO: defined ABC_PrdYildTypeOrder
INFO: defined ABC_ProdArea
INFO: defined ABC_szComDat
INFO: defined ABC_ProdSaleDate
INFO: defined ABC_IsCanBuy
INFO: defined ABC_PurStarAmo
INFO: defined ABC_RowNumber
Dict{String,Array{LibExpat.ETree,1}} with 13 entries:
  "ProdLimit"    => LibExpat.ETree[<ProdLimit>360天</ProdLimit>…
  "ProdSaleDate" => LibExpat.ETree[<ProdSaleDate>18.01.12-18.01…
  "RowNumber"    => LibExpat.ETree[<RowNumber>1</RowNumber>, <R…
  "PurStarAmo"   => LibExpat.ETree[<PurStarAmo>50000.00</PurSta…
  "ProdYildType" => LibExpat.ETree[<ProdYildType>非保本浮动收益…
  "szComDat"     => LibExpat.ETree[<szComDat>2018.01.12</szComD…
  "ProdProfit"   => LibExpat.ETree[<ProdProfit>4.95%</ProdProfi…
  "ProdArea"     => LibExpat.ETree[<ProdArea>全国发行</ProdArea…
  "IsCanBuy"     => LibExpat.ETree[<IsCanBuy>1</IsCanBuy>, <IsC…
  "ProdClass"    => LibExpat.ETree[<ProdClass>封闭</ProdClass>,…
  "ProductNo"    => LibExpat.ETree[<ProductNo>AD180022</Product…
  ⋮              => ⋮

julia> ABC["ProductNo"][1]
<ProductNo>AD180022</ProductNo>

最终您需要使用eval / @eval或定义一个新的宏来生成不带eval的代码,即:

macro process_xpdoc_config(prefix::String, config::String, xp_doc::Symbol)
    _process_xpdoc_config(prefix, config, xp_doc)
end

function _process_xpdoc_config(prefix::String, config::String, xp_doc::Symbol)::Expr
    block = Expr(:block)

    push!(block.args, :(dict = Dict{String, Vector{ETree}}()))

    open(config) do file
        for line in eachline(file)
            if !isempty(line)
                xml = split(line, "=>")

                if length(xml) == 2
                    identifier = Symbol(xml[1])
                    prefixed_identifier = Symbol(uppercase(prefix), '_', identifier)

                    if !isdefined(prefixed_identifier)
                        push!(block.args, esc(:($prefixed_identifier = xp_find($xp_doc, $xml[2]))))
                        info_str = string("defined ", prefixed_identifier)
                        push!(block.args, :(info($info_str)))

                    else
                        warn_str = string(prefixed_identifier, " already defined!")
                        push!(block.args, :(warn($warn_str)))
                    end

                    push!(block.args, :(push!(dict, string($(Meta.quot(identifier))) => xp_find($xp_doc, $xml[2]))))
                end
            end
        end
    end
    push!(block.args, :(dict))
    return block
end

没有eval

的用法宏
julia> DEF_ProdName = 7
7

julia> DEF = @process_xpdoc_config("def", "abc.conf", xp_doc)
INFO: defined DEF_ProductNo
WARNING: DEF_ProdName already defined!
INFO: defined DEF_ProdClass
INFO: defined DEF_ProdLimit
INFO: defined DEF_ProdProfit
INFO: defined DEF_ProdYildType
INFO: defined DEF_PrdYildTypeOrder
INFO: defined DEF_ProdArea
INFO: defined DEF_szComDat
INFO: defined DEF_ProdSaleDate
INFO: defined DEF_IsCanBuy
INFO: defined DEF_PurStarAmo
INFO: defined DEF_RowNumber
Dict{String,Array{LibExpat.ETree,1}} with 13 entries:
  "ProdLimit"        => LibExpat.ETree[<ProdLimit>360天</ProdLi…
  "ProdSaleDate"     => LibExpat.ETree[<ProdSaleDate>18.01.12-1…
  "RowNumber"        => LibExpat.ETree[<RowNumber>1</RowNumber>…
  "PurStarAmo"       => LibExpat.ETree[<PurStarAmo>50000.00</Pu…
  "ProdYildType"     => LibExpat.ETree[<ProdYildType>非保本浮动…
  "szComDat"         => LibExpat.ETree[<szComDat>2018.01.12</sz…
  "ProdProfit"       => LibExpat.ETree[<ProdProfit>4.95%</ProdP…
  "ProdArea"         => LibExpat.ETree[<ProdArea>全国发行</Prod…
  "IsCanBuy"         => LibExpat.ETree[<IsCanBuy>1</IsCanBuy>, …
  "ProdClass"        => LibExpat.ETree[<ProdClass>封闭</ProdCla…
  "ProductNo"        => LibExpat.ETree[<ProductNo>AD180022</Pro…
  "PrdYildTypeOrder" => LibExpat.ETree[<PrdYildTypeOrder>2</Prd…
  "ProdName"         => LibExpat.ETree[<ProdName>“金钥匙·安心得…
julia> DEF<TAB>

julia> DEF
DEF                  DEF_ProdProfit
DEF_IsCanBuy         DEF_ProdSaleDate
DEF_PrdYildTypeOrder DEF_ProdYildType
DEF_ProdArea         DEF_ProductNo
DEF_ProdClass        DEF_PurStarAmo
DEF_ProdLimit        DEF_RowNumber
DEF_ProdName         DEF_szComDat

julia> DEF["ProdName"][1]
<ProdName>“金钥匙·安心得利”2018年第1期多次派息人民币理财产品</ProdName>

请注意,使用do时无需手动关闭文件。

您也可以根据@DNF的建议构建Dict以供日后使用(例如,您可以将其保存,然后再次使用JLD.jl加载),甚至可以同时执行这两项操作。