Power Query:我如何解析列表:单独的键:值列表

问题描述 投票:0回答:1

我想在power query中解析这样的列表

        name: david
 spouse name: rachel 
        kids: 3
        
        name: ronald
 spouse name: dilda
        kids: 2 

结果应该是:

name    spouse name kids
-----   ----------- ----
david   rachel      3
ronald  dilda       2

谢谢!

powerquery m
1个回答
0
投票

基本上,你想做的是

  1. 用空行分割文本,这样您就有了应转换为记录的文本条目列表,
  2. 将每个这样的文本条目转换为记录,然后
  3. 将记录变成表格。

fTextEntryToRecord

首先,创建一个名为“fTextEntryToRecord”的函数查询,给定一个要转换为记录的文本块,该查询将返回一条记录。它可能看起来像这样:

//* If this doesn't work, you can turn it into a normal, debuggable query by changing this line's double-slash to a single slash
(TextEntry as text) as nullable record =>
let
/*/
let
  TextEntry = "       name: david#(lf)" &
              "spouse name: rachel#(lf)" &
              "       kids: 2",
//*/
  Lines = Lines.FromText(TextEntry),
  #"Converted To Record" = List.Accumulate(
    Lines, // process each line
    [], // start with an empty record
    (r, line) => // Function that, given a record and a line of text, adds a field to the record
      let
        FieldValue = Text.Split(line, ": "), // this assumes you'll never have a colon in your data, but I'm sure you can take it from here if this isn't the case.
        Field = Text.Trim(FieldValue{0}),
        Value = Text.Trim(FieldValue{1}),
        #"Added Field" = if (List.Count(FieldValue) = 2) then
          Record.AddField(r, Field, Value)
        else
          r // Note, Power-Query is extremely lazy (i.e. efficient). If FieldValue isn't split into exactly 2 then Field and Value aren't even calculated. 
      in
        #"Added Field"
  ),
  ReturnValue = if (Record.FieldCount(#"Converted To Record") = 0) then
    null
  else
    #"Converted To Record"
in
  ReturnValue

您的询问

现在,一旦“fTextEntryToRecord”查询开始工作(如果必须调试它,请确保将其转换回函数),使用与此类似的代码创建一个新查询:

let
  Source = TextOfYourTextFile,
  #"CRLF to LF" = Text.Replace(Source, "#(cr,lf)", "#(lf)"), // If we can guarantee it's always CRLF or always LF, we don't need this line. Rather than ask, it was easier to take either/or, making the code more robust.
  SplitByBlankLine = Text.Split(#"CRLF to LF", "#(lf,lf)"),
  #"Converted to Records" = List.Transform(
    SplitByBlankLine,
    fTextEntryToRecord
  ),
  #"Converted to Table" = Table.FromRecords(
    List.RemoveNulls(
      #"Converted to Records"
    )
  )
in
  #"Converted to Table"

从那里,您可能想要更改查询以将“年龄”列修改为整数等。由您决定。

© www.soinside.com 2019 - 2024. All rights reserved.