[英]extracting football score from user input
I'm writing a program in python which will deal with user input for football scores. 我正在用python编写一个程序,该程序将处理足球得分的用户输入。 for example: Newcastle United 4 - 6 Manchester united
例如: Newcastle United 4 - 6 Manchester united
above score can also be written as 高于分数也可以写成
NUFC 4-6 MUFC
and also as newcastle 4-6 manu
and so on...... NUFC 4-6 MUFC
以及newcastle 4-6 manu
等...
my purpose is to extract the team names and the score: Newcastle United
, 4
, 6
, Manchester United
. 我的目的是提取球队的名字和比分: Newcastle United
, 4
, 6
, Manchester United
。
I need suggestions on how this can be done. 我需要有关如何完成此操作的建议。 One way i could think of is Regular expression but i'm not well versed with regex, so i am seeking help here. 我能想到的一种方法是正则表达式,但是我对regex不熟悉,因此我在这里寻求帮助。 thanks 谢谢
The following regex would do it: 以下正则表达式可以做到这一点:
^(.*?) *(\d+) *- *(\d+) *(.*)$
Groups: 团体:
This seems to work ... 这似乎起作用...
>>> re.match(r'(.*?)\s*(\d+)\s*\-\s*(\d+)\s*(.*)',s).groups()
('Newcastle United', '4', '6', 'Manchester united')
In general, it looks like a score could be described as a list of 5 items: 通常,得分可以描述为5个项目的列表:
and that there may or may not be a space on either side of the hyphen. 并且连字符的两边可能有也可能没有。
The following should work: 以下应该工作:
g = re.match("(.*) ([0-9]+) ?- ?([0-9]+) (.*)", user_input)
if g:
team1 = g.group(1)
team1_score = g.group(2)
team2_score = g.group(3)
team2 = g.group(4)
The numbers in the call to group()
correspond to the parentheses in the regular expression, from left to right. 对group()
的调用中的数字从左到右与正则表达式中的括号相对应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.