【问题标题】:Searching a list of long strings for a substring and then printing out the next 4 characters在长字符串列表中搜索子字符串,然后打印出接下来的 4 个字符
【发布时间】:2021-12-21 12:15:14
【问题描述】:

感谢您阅读我的问题。我将在我们发言时解决这个问题,如果我找到解决方案,我会更新问题。虽然我担心这对于我的技能来说可能有点太高级了,所以我很感激任何帮助!

我有一个字符串列表,每个字符串都显示一条错误消息。

'Error: Customer (ABC 111) has an activation error'

'Error: Customer (ABC 112) has an activation error'

对于这个 strings 列表中的每个 string 我想找到 substring 'ABC' 然后打印出以下 四个个字符对应ID号。

OUT: ' 111', ' 112'

现在我知道如何在字符串列表中查找子字符串,但是打印以下字符让我感到困惑。

我会在编写代码时进行更新,或者直到一些编码图例帮助我!

谢谢!!

编辑:在下面添加 MRE 和最终代码:

基本上,数据最初是在一个带有两个标题的 excel 文件中提供的,该文件在 Pandas 中被转换为一个数据框。

CONT_ID ERROR_DESC
123 Error: Customer (ABC 111) has an activation error
124 Error: Customer (ABC 112) has an activation error

等等

我需要遍历 ERROR_DESC 列来为每一行选择 CUSTOMER_ID。在现实世界中,数据要复杂一些,在 ID 之前有不同的代码,我还需要字符串中的另一个子字符串。但对于 MRE,我将使用 ABC 作为常数。

我的最终 MRE 代码如下。


cust_id = []
for index, row in df.iterrows():
   desc = row['ERROR_DESC']
   
   i = desc.index('ABC')
   id_num = desc[i+4:1+7]
   cust_id.append(id_num)

【问题讨论】:

  • 看看re 模块
  • 您能发布一个最低限度的可重现示例/示例代码吗?
  • 嗨 Joshua,感谢您提供的模块。我会检查出来的!是的,让我发布一个代码示例,基本上我现在所拥有的(你们很快!)是在数据帧上设置一个 itertuple 操作,以从它们存储的列中获取我想搜索的字符串列表。
  • [a[a.index("ABC"):][3:7] for a in list_of_strings]
  • 如果您正在使用数据框,例如从pandas 开始,肯定有一些方法可以在不使用(可以说是缓慢/低效的)for 循环的情况下做到这一点。

标签: python string list substring


【解决方案1】:

如果没有 MRE 可以使用,我会要求您适当地修改它以适合您的用例:

import re

#setup
list_of_strings = ['Error: Customer (ABC 111) has an activation error',
                   'Error: Customer (ABC 112) has an activation error',
                  ]
pattern = r'(?<=ABC )(\d{3})'

#the thing you want
customer_ids = [int(cust_id.group(0)) for long_string in list_of_strings\
     if (cust_id:=re.search(pattern,long_string))]

#produces
print(customer_ids)

[Out]: [111, 112]

【讨论】:

  • 感谢 Josh 的正则表达式解决方案,我会将此模块合并到未来的正则表达式问题中!
【解决方案2】:

可以获取ABC的索引,在字符串上找到:

a = 'Error: Customer (ABC 111) has an activation error'
i = a.index("ABC")
num = a[i+4:i+7] -> '111'

【讨论】:

  • 太好了,谢谢佩德罗!我会试试这个并重新发布下面的所有代码,这样如果将来有人遇到这个问题,他们可以看到!另外,我会在 8 分钟内接受您的答复。
猜你喜欢
  • 2021-02-24
  • 2014-12-26
  • 1970-01-01
  • 2014-06-03
  • 1970-01-01
  • 1970-01-01
  • 2015-12-20
  • 2020-08-25
  • 1970-01-01
相关资源
最近更新 更多