<p>看起来,它真正需要的是<code>ast.literal_eval</code>。你知道吗</p>
<pre><code>for line in tinputfile:
twoparts = line.split("]")
startlocation = ast.literal_eval(twoparts[0] + ']') # add the ']' back in
# startlocation is now a list of two coordinates.
</code></pre>
<p>但是你最好还是用<code>re</code>。你知道吗</p>
<pre><code>> import re
> example = '[27.994195699999999, -82.569434900000005] 6 2011-08-28 19:02:36 text text text text'
> fmt = re.split(r'\[(-?[0-9.]+),\s?(-?[0-9.]+).\s*\d\s*(\d{4}-\d{1,2}-\d{1,2}\s+\d{2}:\d{2}:\d{2})',example)
> fmt
['', '27.994195699999999', '-82.569434900000005', '2011-08-28 19:02:36', ' text text text text']
> location = (float(fmt[1]), float(fmt[2]))
> time = fmt[3]
> text = fmt[4]
</code></pre>
<p>怎么回事?你知道吗</p>
<p>正则表达式(<code>re</code>模块)中的每一个<code>(...)</code>都告诉<code>re.split</code>“将此片段作为自己的索引”。你知道吗</p>
<p>第一个和第二个是<code>-?[0-9.]</code>。这意味着匹配任何可能有一个负号后接数字和小数位(我们可以更严格,但你真的不需要)。你知道吗</p>
<p>下一组<code>()</code>匹配任何日期:<code>\d{4}</code>表示“四位数”。<code>\d{1,2}</code>表示“一个或两个数字”。你知道吗</p>
<p>或者,您可以同时使用这两者:</p>
<pre><code>> fmt = re.split(r'\[(-?[0-9.]+,\s?-?[0-9.]+).\s*\d\s*(\d{4}-\d{1,2}-\d{1,2}\s+\d{2}:\d{2}:\d{2})',example)
> fmt # watch what happens when I change the grouping.
['', '27.994195699999999, -82.569434900000005', '2011-08-28 19:02:36', ' text text text text']
> location = literal_eval('(' + fmt[1] + ')')
> time = fmt[2]
> text = fmt[3]
</code></pre>