gpt4 book ai didi

python - 仅从提到关键字的字符串中提取数字

转载 作者:行者123 更新时间:2023-12-02 15:50:28 24 4
gpt4 key购买 nike

我有 4 个元素存储在一个数组中,我只想从提到 Approved 关键字的字符串中获取整数。

my_array = ['STK72184 4/28/2022 50 from Exchange Balance, 50 from Earning Balance & 10 from Bonus 25000 Regular 10/20/2023 Approved 4/28/2022',
'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 5000 Regular 10/19/2023 Closed 4/27/2022',
'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 15000 Regular 10/19/2023 Closed 4/27/2022',
'STK722222 4/26/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 10000 Regular 10/18/2023 Approved 4/26/2022']

到目前为止,我只能通过这样做从列表中获取整数:

import re

# Print integers
nums = [int(re.search(r'\d+000', s)[0]) for s in my_array]
print(nums)

# Printed output:
# [25000, 5000, 15000, 10000]

预期输出是:

[25000,10000]

最佳答案

使用list comprehensionre.search和一个 if。请注意,第二个示例表明基于正则表达式的搜索可以非常强大地只提取您想要的模式,因此我几乎总是更喜欢它而不是精确的字符串匹配(除非性能很关键)。另外,我把array重命名为lst(这个数据结构在Python里叫list,其他一些语言叫array)。

import re

my_lst = ['STK72184 4/28/2022 50 from Exchange Balance, 50 from Earning Balance & 10 from Bonus 25000 Regular 10/20/2023 Approved 4/28/2022',
'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 5000 Regular 10/19/2023 Closed 4/27/2022',
'STK725721 4/27/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 15000 Regular 10/19/2023 Closed 4/27/2022',
'STK722222 4/26/2022 50 from Exchange Balance, 40 from Earning Balance & 10 from Bonus Balance 10000 Regular 10/18/2023 Approved 4/26/2022']

nums = [int(re.search(r'\d+000', s)[0]) for s in my_lst if re.search(r'Approved', s)]
print(nums)
# [25000, 10000]

nums = [int(re.search(r'\d+000', s)[0]) for s in my_lst if re.search(r'4/2[67]', s)]
print(nums)
# [5000, 15000, 10000]

关于python - 仅从提到关键字的字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72664180/

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