简体   繁体   English

从用户输入中提取足球得分

[英]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 United46Manchester 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: 团体:

  • Group 1: Left team 第一组:左团队
  • Group 2: Left team score 第二组:左队得分
  • Group 3: right team score 第三组:正确的球队得分
  • Group 4: right team 第4组:正确的团队

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个项目的列表:

  1. arbitrary text 任意文字
  2. a string of digits 一串数字
  3. a hyphen 连字符
  4. a string of digits 一串数字
  5. arbitrary text 任意文字

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM