Mathematica - 将字符串的元素分隔成列?

时间:2011-07-01 20:22:55

标签: string list wolfram-mathematica

我正在生成编码输出,这是一个看起来像列表的字符串列表。有没有办法将它们变成实际列表,以便我可以选择元素并将它们格式化为列?或者一种在字符串中选择字符并将它们放在列中的方法?

  Button[
    "Run",
    {afit = Input["Please Enter ID#", deleteme] ;
    ClearAll[dat],
    dat := TraumaEncoding@afit;
    ClearAll[funcel],
    funcel[p_String] :=
     Which[StringMatchQ[
      p, ("*no new ones*" | "*no new marks*" | 
      "*old wounds healing*"), 
      IgnoreCase -> True], "0",
      StringMatchQ[p, ("*abrasion*"), IgnoreCase -> True], "{1,0}",
      StringMatchQ[p, ("*lacer*"), IgnoreCase -> True], "{1,1}",
      StringMatchQ[p, ("*punct*") | ("*pct*"), 
      IgnoreCase -> True], "{1,2}",
      StringMatchQ[p, ("*amput*"), IgnoreCase -> True], "{1,4}",
      StringMatchQ[
       p, ("*wound*" | "*injur*" | "*trauma*" | 
       "*swollen*" | "*swell*"), IgnoreCase -> True], 1, True, 0];
    funcel[___] := 0;
    ClearAll[func],
    func[l_List] := 
     Which[MemberQ[Map[funcel, l], "0"], "0", 
      MemberQ[Map[funcel, l], "{1,4}"], "{1,4}", 
      MemberQ[Map[funcel, l], "{1,2}"], "{1,2}", 
      MemberQ[Map[funcel, l], "{1,1}"], "{1,1}", 
      MemberQ[Map[funcel, l], "1-0"], "1,0", MemberQ[Map[funcel, l], 1],
       1, True, 0];
    listo := Map[func, dat]},
  Background -> Yellow, Sequence @@ $ButtonOptions
  ]

产生类似的东西:

   {"{1,2}", "{1,2}", "0", "{1,2}", "0", "0", "0", "0", "0"}

我需要把它变成更像这样的东西,理想情况下我可以导出到Excel文件中:

    Header  Header
      1       2
      1       2
      0
      1       2
      0
     etc.,

2 个答案:

答案 0 :(得分:2)

一个小注意事项:您实际上不需要Map ToExpression到列表中,而是可以Apply

In[91]:= ToExpression@{"{1,2}","{1,2}","0","{1,2}","0","0","0","0","0"}
Out[91]= {{1,2},{1,2},0,{1,2},0,0,0,0,0}

答案 1 :(得分:1)

ToExpression["{1,2}"]

==> {1,2}

或整个清单:

data =
 Prepend[ToExpression /@ {"{1,2}", "{1,2}", "0", "{1,2}", "0", "0", 
    "0", "0", "0"}, {"header1", "header2"}]

(* ==> {{"header1", "header2"}, {1, 2}, {1, 2}, 0, {1 2}, 0, 0, 0, 0, 0}   *)

格式化为表格:

enter image description here

要导出:

Export["filename.csv", data]