python-如何使用法语语法分析字符串以获取'/'两侧的数字

我正在尝试在python中解析一个包含分数的字符串,在该字符串中,我需要将分数两侧的数字存储为不同的变量。它适用于两面都是一位数字,但是当有两位数字时,我只是得到一个数字的“ /”符号,而只有第二部分的第一个数字。输入文件如下所示:

product/productId: B001EO5QW8
review/userId: AOVROBZ8BNTP7
review/profileName: S. Potter
**review/helpfulness: 19/19**
review/score: 4.0

我的代码如下:

if 'review/helpfulness' in line:
    helpline = line.rstrip().split(': ')[1:] 
    number_voted = helpline[0][0]
    number_rated = helpline[0][2]

我得到这个答案:

NumHelpfulVotes         NumVotes
   1                       /
feiyuemiwu00 回答:python-如何使用法语语法分析字符串以获取'/'两侧的数字

一种解决方案是用斜杠进一步分割:

numbers = line.split(':')[1].strip().split("/")
# ['19','19']

另一种解决方案是使用正则表达式搜索:

import re 
numbers = re.findall("(\d+)/(\d+)",line)[0]
#('19','19')
本文链接:https://www.f2er.com/3087906.html

大家都在问