Skip to main content
 首页 » 编程设计

Python之使用正则表达式获取用户数据

2025年05月04日31lhb25

所以,我仍然是 regex 和 python 的新手。我已经搜索了一段时间,但不知道如何询问我在寻找什么。

我需要将格式化字符串中的数据放入列表列表或字典中。

------------------------------------------------------------------- 
Frank         114      0         0         0          0         114        
Joe           49       1         0         0          0         50         
Bob           37       0         0         0          0         37         
Sally         34       2         0         0          0         36      

这是脚本的输出。目前我有:

match_list = [] 
match = re.search('\n(\w+)\s+(\d*)\s+(\d*)', output) 
  if match: 
    match_list.append([match.group(1), 
                       match.group(2), 
                       match.group(3)]) 
>>>print match_list 
[['frank', '114', '0']] 

这是完美的,除了我需要让 match_list 返回:

[['frank', '114', '0'], 
 ['Joe', '49', '1'], 
 ['Bob', '37', '0'], 
 ['Sally', '34', '2']] 

我最初的想法是 for 循环,并检查 match.group(1) 是否已经列出,如果是则转到下一个,但后来我意识到我不知道该怎么做。但是你现在有了。我很难弄清楚这一点。任何帮助都会很棒! :)

还有哦。列表大小发生变化。有时可能只有一个用户,有时可能有 20 个用户。所以我可以设置一个巨大的静态正则表达式。 (据我所知...)

请您参考如下方法:

您可以使用 re.findall :

match_list = [] 
match = re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output) 
for k in match: 
    #k will be a tuple like this: ('frank', '114', '0') 
    match_list.append(list(k)) 

或者 与 oneliner 相同的解决方案:

match_list = map(list, re.findall('\n(\w+)\s+(\d*)\s+(\d*)', output))