<p>假设我有一个文本文件,其中的数字由冒号和空格分隔,如下所示。你知道吗</p>
<pre><code>0:-83 1: -51 2: -69 3: -82 4: -85 8: -90 9: -69 QUAD
0:-88 1: -88 2: -98 3: -75 4: -42 5: -71 6: -89 7: -28 8: -83 9: -78 STADIUM
</code></pre>
<p>一对是由冒号分隔的两个数字。空格任意中断数对。你知道吗</p>
<p>目前,我有以下几点。你知道吗</p>
<pre><code>with open('data.txt') as file:
lines = file.read().splitlines()
for line in lines:
line = line[:-1]
# What is the regex I should be using?
# data = re.split(r'[:\s]',line) includes the space after the colon if it exists
</code></pre>
<p>解析文本文件的最佳方法是什么,以便每一行都存储为一个元组列表,其中每个元组都是一对?你知道吗</p>
<p>首先,编写<code>for line in file:</code>代码要简单得多
你可以用Martijn的正则表达式来计算数字。你知道吗</p>
<pre><code>for line in file:
marker = line.split()[-1]
numbers = re.findall(r'\b(\d+)\s*:\s*(\d+)\b', line)
</code></pre>