我想在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
谢谢!
基本上,你想做的是
首先,创建一个名为“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"
从那里,您可能想要更改查询以将“年龄”列修改为整数等。由您决定。