Python正则表达式将一个段落分成句子,每个句子都以一个名字开头

时间:2017-07-20 04:30:44

标签: python regex

我希望能够将一段句子分成子串,其中段落在每个句子的末尾分开。每个新句子都以玩家的名字开头。我的主要问题是在每个句子的开头适应玩家姓名的所有潜在格式。以下是一些例子:

INPUT:

Kentucky 1st - T. Pompey grounded out to 2b (2-0 BB). E. White lined out to cf (1-0 B). Z. Reks homered to right field, RBI (3-2 BFBBK). K. Cottam struck out swinging (1-2 KKBS). 

UT Martin 2nd - KERWIN struck out looking (1-2 KSBK). ELDRIDGE fouled out to 3b (1-0 B). WESSLING walked (3-2 BKKBBK). STEEN reached on an error by ss (0-0); WESSLING advanced to second.

Belmont 2nd - EGLI, N. grounded out to 3b (0-1 K). BOURNIGAL, R walked (3-2 BSKBBB). KOCHER, B. walked (3-1 FBBBB); BOURNIGAL, R advanced to second. KOCHER, B. advanced to second; BOURNIGAL, R advanced to third on a throwing error by p.

Murray State 3rd - Bence, A. singled to left field (2-0 BB). Bence, A. stole second. Bauer, A. flied out to lf to left center (2-1 FBB); Bence, A. advanced to third. Gutzler, B. flied out to lf, SAC, RBI (1-0 B); Bence, A. scored. Hranec, J. fouled out to 1b (0-0). 

期望的输出:

'Kentucky 1st - '
'T. Pompey grounded out to 2b (2-0 BB).'
'E. White lined out to cf (1-0 B).'
'Z. Reks homered to right field, RBI (3-2 BFBBK).'
'K. Cottam struck out swinging (1-2 KKBS).'

'UT Martin 2nd - '
'KERWIN struck out looking (1-2 KSBK).'
'ELDRIDGE fouled out to 3b (1-0 B).'
'WESSLING walked (3-2 BKKBBK).'
'STEEN reached on an error by ss (0-0); WESSLING advanced to second.'

'Belmont 2nd - '
'EGLI, N. grounded out to 3b (0-1 K).'
'BOURNIGAL, R walked (3-2 BSKBBB).'
'KOCHER, B. walked (3-1 FBBBB); BOURNIGAL, R advanced to second.'
'KOCHER, B. advanced to second; BOURNIGAL, R advanced to third on a throwing error by p.'

'Murray State 3rd - '
'Bence, A. singled to left field (2-0 BB).'
'Bence, A. stole second.'
'Bauer, A. flied out to lf to left center (2-1 FBB); Bence, A. advanced to third.'
'Gutzler, B. flied out to lf, SAC, RBI (1-0 B); Bence, A. scored.'
'Hranec, J. fouled out to 1b (0-0).'

我尝试提供以下输出的代码如下(注意以下代码中的'团队'只是指代开始该段落的团队 - 例如Kentucky,UT Martin或Belmont:

s = re.split(r'[.][ ](?=[A-Z][^.])|[.][ ](?=[0-9])', s)
for i, x in enumerate(s):
     x = x.split('.')[0]
     if ' - ' in x:
          team = '\n' + re.split(r'[0-9]', x.split(' - ')[0])[0].replace(';','').strip()
          print(team + '\n')
          y = x.split(' - ')[1] + '.'
          if len(y)>2:
               print(y + '\n')
          else:
               x = x + '.'
               print(x + '\n')

1 个答案:

答案 0 :(得分:1)

如果您以不同方式制定模式,那么您可能不需要进行任何枚举:

import hudson.model.*;

stage('Checkout') {
    node{
        git branch: '<BRANCH_NAME>', credentialsId: '<JENKINS_CREDENTIAL_ID>', url: 'git@<URL_OF_YOUR_FORKED_REPOSITORY>'
    }
}

stage('Build'){
    node{
        "build project"
    }
}

<强>结果

s = re.split(r'([a-zA-Z0-9 ]+[^-] -|[A-Z][.][ ][^.]+|[A-Z]+[,.]*[ ]*[A-Z]*[,.]*[ ][^.]+)|.', s)
s = filter(None, s)

for v in s:
    print(v.strip('\n\n'))

示例

https://repl.it/JaIW/1