Python排序正则表达式

2024-09-28 22:41:19 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,制作一个文件,通过一个txt文件排序,并选择名称:和前3个统计数据,并存储在一个dict,然后做同样的下一个名称+3统计如果dict是不聪明的存储在一个列表中他们也会工作,我想。你知道吗

txt文件如下所示:

player a 34 45 56 player b 38 93 75 playerc 39 29 18 playerd 38 98 

我试过player = re.findall(r"[-+]?\d*\.\d+|\d+", player_string) 但它只给我的球员评分,我想我需要使用某种dict来存储所有不同的球员。你知道吗

如果这很复杂,你不必为我做所有的事情,只要给我指出正确的方向。 非常感谢。 我用的是py2.6


Tags: 文件retxt名称列表string排序评分
3条回答

我想你需要的是:

import re

player_string = "player a 34 45 56 player b 38 93 75 playerc 39 29 18 playerd 38 98"

pattern = re.compile(r"player\s+(\w+)\s+(\d+)\s+(\d+)\s+(\d+)")
matches = pattern.findall(player_string)
d = {}
for m in matches :
    print m
    d[m[0]] = m[1:]

print d

注意,你写的“playerc”和“playerd”没有空格,这两个将不会被找到。你知道吗

我想这可能会给你一些你想要的东西,尽管不使用正则表达式:

my_list = # list of players and stats from above

# build a list by splitting the original string at the word "player"
# and stripping extra white space
my_list_split = [item.strip() for item in my_list.split("player")]

这将给出一个类似于['', 'a 34 45 56', ...]的列表,其中每个元素都应该包含不同播放器的信息。接下来,我们将这些元素拆分为一个字典,其中玩家名称是键,统计数据是值:

my_dict = {}  # initialize the dictionary
for entry in my_list_split:
  if entry is not "":  # possible you will have a blank string at the beginning
    entry_list = entry.split(" ")  # split entry at spaces
    my_dict[entry_list[0]] = entry_list[1:]  # first element is the name, remaining elements are the stats

你可以修改它,只获得前两个或三个属性,或者改变属性的存储方式。您给出的列表上的结果my_dict.items()是:

[('a', ['34', '45', '56']),
 ('c', ['39', '29', '18']),
 ('b', ['38', '93', '75']),
 ('d', ['38', '98'])]

我想你需要的是:

import re

player_string = "player a 34 45 56 player b 38 93 75 playerc 39 29 18 playerd 38 98"

pattern = re.compile(r"([\w ]*?)\s+(\d+)\s+(\d+)\s+(\d+)")
matches = pattern.findall(player_string)
d = {}
for m in matches :
    print m
    d[m[0].strip()] = m[1:]

print d

在最后一个玩家“playerd”之后,你只有2个数字,而不是regex期望的3个。你知道吗

输出:

{'playerc': ('39', '29', '18'), 'player b': ('38', '93', '75'), 'player a': ('34', '45', '56')}

相关问题 更多 >