使用Split或Regex提取UFC选手战绩:无法获取平局数的问题
解决UFC选手胜-负-平数据提取问题
原代码问题分析
你的代码无法输出平局数的核心原因有两个:
- 循环遍历
correctRecord的索引,但判断的是原record字符串的字符,两者长度不一致,且correctRecord本身只有两个-,循环中totaldash最多只能到2,永远触发不了第三个分支(平局输出)。 - 变量复用混乱,用
totalwins临时存储所有阶段的数据,逻辑容易出错,且最后一段平局数据没有触发输出的时机。
修复原代码方案
调整循环判断对象,并在循环结束后主动输出平局数,同时拆分变量避免混淆:
import re record = "10-7-3 (W-L-D)" # W = wins, L= Loss, D= Draws char = "-" totalwins = "" totalloss = "" totaldraws = "" correctRecord = re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+', record)[0] print("The correct record per fighter is:", correctRecord) totaldash = 0 for i in range(len(correctRecord)): if correctRecord[i] == char: totaldash += 1 if totaldash == 1: print("The total wins", totalwins) totalloss = "" totalwins = "" elif totaldash == 2: print("The total losses ", totalloss) totaldraws = "" totalloss = "" else: # 根据当前dash数量分配到对应变量 if totaldash == 0: totalwins += correctRecord[i] elif totaldash == 1: totalloss += correctRecord[i] elif totaldash == 2: totaldraws += correctRecord[i] # 循环结束后输出最后一段平局数据 print("The total draws ", totaldraws)
更简洁的实现方案
既然correctRecord是标准的W-L-D格式字符串,直接用split("-")分割即可,无需复杂循环:
import re record = "10-7-3 (W-L-D)" # 提取核心胜败平数据 correctRecord = re.findall('\[[^\]]*\]|\([^\)]*\)|\"[^\"]*\"|\S+', record)[0] # 按"-"分割为三个部分 wins, losses, draws = correctRecord.split("-") print("The correct record per fighter is:", correctRecord) print(f"The total wins {wins}") print(f"The total losses {losses}") print(f"The total draws {draws}")
关于你尝试的strip方法无效的说明
你之前写的correctRecord= str(record.split(separator, 1)[0])存在两个问题:
- 未定义
separator变量,代码会报错; - 即使改为
split("-", 1),也只会将字符串分割为["10", "7-3 (W-L-D)"],只能提取到胜场数,无法获取负场和平局数,因此无法解决问题。
内容的提问来源于stack exchange,提问作者newbie19901
相关产品推荐
相关产品推荐

