python - 在 Python 中使用某些参数拆分列表。使用 re.findall

标签 python

import re

def processFile(filename='Names.txt', encode='utf-8'):
    listOfPlayers = []
    listOfInfo = []
    count = 0
    with open(filename, 'r', encoding = encode) as f:
        for line in f.readlines():
            if count == 0:
                listOfInfo.append(line.strip())
                count += 1
            elif count == 1:
                listOfInfo.append(line.strip())
                listOfPlayers.append(listOfInfo)
                count -= 1
                listOfInfo = []
    return listOfPlayers

def splitStats(listOfPlayers):
    newList = []
    for item in (i[1] for i in listOfPlayers):
        m = re.findall('[A-Z][a-z]*', item)
        newList.append(m)
    print(newList)    

def main():
    lOP = processFile()
    splitStats(lOP)

if __name__ == '__main__':
    main()

我正在尝试查看一些足球统计数据,并从网页上获取了一些统计数据,并尝试将每个球员的位置、国家/地区、他们转会的来源、转会的目的地以及所获得的资金分开为他们付出了代价。

My Names.txt 文件如下所示:

Donyell Malen
AttackerNetherlandsArsenalAjaxUndisclosed
Petr Cech
GoalkeeperCzech Rep.ArsenalChelsea14million
Scott Sinclair
MidfielderEnglandAston VillaManchester City3.4million

我的 processFile 中的 listOfPlayers 有一个列表列表。将玩家作为索引零,其余信息如下所示:

[['Donyell Malen', 'AttackerNetherlandsArsenalAjaxUndisclosed'], ['Petr Cech', 'GoalkeeperCzech Rep.ArsenalChelsea14million'], ['Scott Sinclair', 'MidfielderEnglandAston VillaManchester City3.4million'],

我正在尝试解析每个项目和 1 索引以将其拆分。我找到了 re.findall() 方法,但搜索了 API 一个小时,仍然没有清楚地了解如何与大写字母分开(尽管代码是这样做的)我需要保留任何两个单词之间有一个空格作为一个字符串。即“Aston Villa”应该保留在一起,以及如何将其中的费用(即“340万”)保留为340万。

我知道这是一个很长的问题,但我想给出一个很好的概述,看看我是否在做这一切都是错误的,或者我是否走在正确的轨道上,只需要 re.findall( )。谢谢!

最佳答案

您可以使用以下模式

"(?:[A-Z]|[0-9]+(?:.[0-9]+)?)[a-z]*(?: [A-Z][a-z]*)*"

它非常复杂,因为它基本上处理所有特殊情况 如果您对如何编写此类表达式感兴趣,您应该深入研究 re 模块的文档 https://docs.python.org/2/library/re.html

关于python - 在 Python 中使用某些参数拆分列表。使用 re.findall,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33447272/

相关文章:

python - 从 SQL 查询生成绘图数据表

python - 在 block 之前和之后运行一些通用代码

python - 运行终端命令但不通过 python 显示输出

python - 我想用一个包含 python 中的 longs 和 ints 的列表来调用 reduce

python - Redshift + SQLAlchemy 长查询挂起

Python matplotlib 给文本添加超链接

python - 我如何能够加快 Matlab 中的滑动窗口以进行操作对象识别?

python - 如何在 Python 中获得人类可读的时区名称?

python - from random import choice as rc 中的 rc 是做什么的?这是 python

python - Python GUI 中的实时绘图