有没有办法从这样的字符串中获得选择性数据?

2024-09-19 14:20:25 发布

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

我正在开发一个程序,它可以获取如下字符串:

s = 'GPA: 3.4 GRE: 317 Round: Round 2 | West'
d = 'GPA: 3.7 GRE: 328 Round: Round 3 | Singapore'
a = 'GPA: undergrad: 3.68 grad: DPT 3.32 GMAT Waiver Round: Round 3'
c = 'GPA: 3.2 GMAT: 750 Round: Rolling Admissions | NY'

到目前为止,我只是使用重表达式获取轮数。 但对于像c这样的例外情况,我也需要让它返回“滚动录取”。有没有办法在圆形标志和管道标志之间获取数据

我一直在这样做:

R = re.findall('\S*Round ([a-zA-Z0-9]+)', d)
print(''.join(R))

Tags: 字符串程序标志gpawestrollingdptround
2条回答

下面的正则表达式获取两个delimter Round: |之间的值

import re

c = 'GPA: 3.2 GMAT: 750 Round: Rolling Admissions | NY'
R = re.findall('Round\: (.*?) \|', c)
print(R) # output: 'Rolling Admissions'

编辑: 注意,有几个实例中管道标志不可用。使用以下命令将搜索Round: 之后和 |之前的字符串,或搜索到字符串的结尾

import re

s = 'GPA: 3.4 GRE: 317 Round: Round 2 | West'
d = 'GPA: 3.7 GRE: 328 Round: Round 3 | Singapore'
a = 'GPA: undergrad: 3.68 grad: DPT 3.32 GMAT Waiver Round: Round 3'
c = 'GPA: 3.2 GMAT: 750 Round: Rolling Admissions | NY'

print(re.findall('Round: (.*?) ($|\|)', s)) #output: [('Round 2', '|')]
print(re.findall('Round: (.*?) ($|\|)', d)) #output: [('Round 3', '|')]
print(re.findall('Round: (.*?) ($|\|)', a)) #output: [('Round 3 ', '|')]
print(re.findall('Round: (.*?) ($|\|)', c)) #output: [('Rolling Admissions', '|')]

您只需要获取第一个元素,这将是您请求的值

例如

value = re.findall('Round: (.*?) ($|\|)', c)) #output: [('Rolling Admissions', '|')]
print(value[0][0]) # since the output is a tuple within a list

给你

c = 'GPA: 3.2 GMAT: 750 Round: Rolling Admissions | NY'
c.split('|')[0]

相关问题 更多 >