感謝您閱讀我的問題。我將在我們發言時解決這個問題,如果我找到解決方案,我會更新問題。雖然我擔心這對我的技能來說可能有點太高級了,所以我很感激任何幫助!
我有一個字串串列,每個字串都顯示一條錯誤訊息。
'Error: Customer (ABC 111) has an activation error'
'Error: Customer (ABC 112) has an activation error'
對于每一個字串在這個名單串,我想找到字串“ABC”,然后列印出以下4級,其分別對應的ID號人物。
OUT: ' 111', ' 112'
現在我知道如何在字串串列中查找子字串,但是列印以下字符讓我感到困惑。
我會在我完成代碼時更新,或者直到一些編碼圖例幫助我!
謝謝!!
編輯:在下面添加 MRE 和最終代碼:
本質上,資料最初是在一個帶有兩個標題的 Excel 檔案中提供的,這些標題在 Pandas 中被轉換為一個資料框。
| CONT_ID | ERROR_DESC |
|---|---|
| 123 | 錯誤:客戶 (ABC 111) 有激活錯誤 |
| 124 | 錯誤:客戶 (ABC 112) 有激活錯誤 |
等等。
我需要遍歷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)
uj5u.com熱心網友回復:
您可以獲取的索引ABC并在字串上找到它:
a = 'Error: Customer (ABC 111) has an activation error'
i = a.index("ABC")
num = a[i 4:i 7] -> '111'
uj5u.com熱心網友回復:
如果沒有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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/353093.html
上一篇:PythonFor回圈作業
下一篇:檢查字典值中是否存在串列元素
