gpt4 book ai didi

python - 在python中使用正则表达式在字符串列表中查找匹配关键字后的下一个单词

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

我有一个字符串列表,我想在每个字符串中的特定关键字之后提取下一个单词。
当我使用 lambda 函数遍历列表时,我得到的是整个字符串,而不仅仅是关键字后面的下一个词:

import re
s = ["The job ABS is scheduled by Bob.", "The job BFG is scheduled by Alice."]
user = filter(lambda i:re.search('(?<=The job )(\w+)',i),s)
print(*user)

output: The job ABS is scheduled by Bob. The job BFG is scheduled by Alice.
但是,当我为单个字符串尝试相同的代码时,它给出了正确的输出:
import re
s = "The job ABS is scheduled by Bob."
user = re.search('(?<=The job )(\w+)',s)
print(user.group())

output: ABS
如何从第一个代码片段中获得像 (ABS, BFG) 这样的输出?

最佳答案

您可以使用

import re
s = ["The job ABS is scheduled by Bob.", "The job BFG is scheduled by Alice."]
rx = re.compile(r'(?<=The job )\w+')
user = tuple(map(lambda x: x.group() or "", map(rx.search, s)))
print(user)
Python demo .
或者,如果可以有任意数量的空格,请使用
rx = re.compile(r'The\s+job\s+(\w+)')
user = tuple(map(lambda x: x.group(1) or "", map(rx.search, s)))
输出:
('ABS', 'BFG')
在这里, map(rx.search, s)返回匹配数据对象的迭代器或 None s 和外 map(lambda x: x.group(...) or "", ...)获取组的值(与 .group() 的整个匹配或与 .group(1) 的组 1 值),如果没有匹配,则返回空字符串。

关于python - 在python中使用正则表达式在字符串列表中查找匹配关键字后的下一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65725286/

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