Python:如何在另一个指定字符串之后提取字符串

2024-09-30 02:35:16 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个字符串列表,如下所示。你知道吗

lst_1 = ['foo','bar','Invoice No: SME2324-AA']
lst_2 = ['trincas','hotel park','delivery date 12-sept-2019','invoice no: 11245']

目标: 我想从这两张清单中提取发票号码。你知道吗

我目前的做法是:

lst_3 = [lst_1,lst_2]
txt=[]
for inv_no in lst_3:
    for i in inv_no:
         z = i
         inv = re.search(r'Invoice (\S+) (.+?)',' '.join(z))
         txt.append(inv)

当我想看到输出,即txt时,我得到

[None, None, None, None, None, None, None, None]

我要找的是

['SME2324-AA','11245']

我错过了什么?任何帮助都将不胜感激。你知道吗


Tags: no字符串intxtnone列表forfoo
3条回答

不使用regex,您可以这样尝试:

lst_3 = lst_1 + lst_2
txt=[]
for i in lst_3:
    if 'invoice' in i.lower():
        txt.append(i.split()[-1])
print (txt)

输出:

['SME2324-AA', '11245']
  • 首先,' '.join使每个元素之间都有空格。你知道吗
  • 其次,(.+?)在第一次匹配时停止(即非贪婪),而r'Invoice...'在小写invoice时必然失败。你知道吗
  • 第三,append(inv)实际上不会附加匹配结果;您需要指定group:if inv: text.append(inv.group(2)

解决所有问题:

lst_3 = [lst_1,lst_2]
txt=[]
for inv_no in lst_3:
    for i in inv_no:
        z = i
        inv = re.search(r'[Ii]nvoice (\S+) (.+)',z)
        #                      group(1)^    ^group(2)
        if inv:
             txt.append(inv.group(2))
txt

输出:

['SME2324-AA', '11245']

通过将re.findallre.IGNORECASE一起使用,可以使其更简单:

import re

res = []
for i in lst_1 + lst_2:
    res.extend(re.findall('invoice no: (.+)', i, re.IGNORECASE))
res

输出:

['SME2324-AA', '11245']

我们可以尝试将您的列表合并成一个字符串,然后使用re.findall查找所有发票号码:

lst_1 = ['foo','bar','Invoice No: SME2324-AA']
lst_2 = ['trincas','hotel park','delivery date 12-sept-2019','invoice no: 11245']
lst_all = lst_1 + lst_2
inp = " ".join(lst_all)
invoices = re.findall(r'\binvoice no: (\S+)', inp, flags=re.IGNORECASE)
print(invoices)

这张照片:

['SME2324-AA', '11245']

相关问题 更多 >

    热门问题