从文本文件,空格,拆分字母和数字以及冒号中提取数据

时间:2016-10-22 13:29:10

标签: python

我正在尝试创建一个程序,该程序读取下面格式超过1000行的txt文件,并将数据存储在两个独立的二维数组中:

b14 b15 b12 y4:y11 r7 y1 b2
r15 y13 y12 b14:g9 r2 b8 b7

该文件存储游戏的结果,其中有两个玩家,他们都从一个包中选择四个令牌。上面可以看到的示例标记是'b15',这意味着它是蓝色并且其上具有数字15。冒号表示此后的代币是第二个玩家。

每一行都是游戏。我需要将每个标记的颜色和数量存储到具有4行和2列的二维数组中,每个玩家都有一个例如。

player1[0][0] = 'b'
player1[0][1] = 14
player1[1][0] = 'b'
player1[1][1] = 15

这为玩家1存储了前两个令牌,之后我为这个玩家存储了其余的令牌,而第二个玩家在单个游戏中存储了单独的二维数组(文本文件中的单行),I'将处理数据然后再次覆盖数组以用于文本文件中的下一行(游戏)。

我的主要问题是如何执行以下操作:

  • 拆分字母和数字,以便将它们存储在单独的数组位置
  • 识别空格,表示新令牌
  • 认识到冒号意味着玩家的所有代币都已被选中,接下来是玩家2。

感谢阅读,我很乐意回答任何问题以进一步澄清。

3 个答案:

答案 0 :(得分:1)

您已从文本文件中读取了一个动作,您可以使用拆分功能和列表切片(Explain Python's slice notation)来处理它们。

>>> mystring = 'b14 b15 b12 y4:y11 r7 y1 b2'

在冒号处拆分以获得玩家1 /付款人2的移动:

>>> player1, player2 = mystring.split(':')

对于每个玩家,在空格处分开以获得移动:

>>> player1_moves = player1.split(' ')
>>> player1_moves
['b14', 'b15', 'b12', 'y4']

如果您知道移动的第一部分将始终只是一个字母,那么您可以“切片”'关闭字符串的第一部分:

>>> player1_moves[0][:1]
'b'
>>> player1_moves[0][1:]
'14'

答案 1 :(得分:1)

你可以使用正则表达式来分割字母和数字,str.split()来分割2个玩家'结果

import re

for line in file(yourfilename):
    line = line.strip()
    if line != '':#not white space
        results = line.split(':')#results[0] is the first man's result,results[1] is the second man's result
        result1 = results[0].split(' ')
        player1 = []
        for i in range(4):
            grade = re.findall(r'([a-z]+)([0-9]+)', result1[i])
            player1.append([grade[0][0],grade[0][1]])#Split the letter and number
        #player2 is the same as player1

答案 2 :(得分:1)

使用以下方法(关键功能为re.matchstr.split):

import re

# str represents the line form text file
str = 'b14 b15 b12 y4:y11 r7 y1 b2'
player1, player2 = [[list(re.match('^([a-z])(\d+)$', i).groups()) for i in player.split(' ')]
                    for player in str.split(':')
                    ]

print(player1, player2, sep='\n')

输出:

[['b', '14'], ['b', '15'], ['b', '12'], ['y', '4']]
[['y', '11'], ['r', '7'], ['y', '1'], ['b', '2']]