gpt4 book ai didi

python - 在python中使用正则表达式排除模式

转载 作者:行者123 更新时间:2023-12-04 08:25:17 25 4
gpt4 key购买 nike

我想从给定的字符串中提取 Name 和 number 并将其保存到两个列表中。

    str = 'Dhoni scored 100 runs and Kohli scored 150 runs.Rohit scored 50 runs and Dhawan scored 250 runs .'
我想实现:
    name = ['Dhoni','Kohli','Rohit','Dhawan']
values = ['100','150','50','250']
我尝试使用负面展望,但没有成功。我试图使用这种方法来匹配一个词,然后是一个数字,然后是一个词。可能是我在这种方法上错了。如何做到这一点?
我试过的:
   pattern = r'^[A-Za-z]+\s(?!)[a-z]'
print(re.findall(pattern,str))

最佳答案

您可以改用 2 个捕获组:

\b([A-Z][a-z]+)\s+scored\s+(\d+)\b
regex demo
import re

pattern = r"\b([A-Z][a-z]+)\s+scored\s+(\d+)\b"
str = "Dhoni scored 100 runs and Kohli scored 150 runs.Rohit scored 50 runs and Dhawan scored 250 runs ."

matches = re.finditer(pattern, str)
name = []
values = []
for matchNum, match in enumerate(matches, start=1):
name.append(match.group(1))
values.append(match.group(2))

print(name)
print(values)
输出
['Dhoni', 'Kohli', 'Rohit', 'Dhawan']
['100', '150', '50', '250']

关于python - 在python中使用正则表达式排除模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65292624/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com