如何从SMS文本字符串创建模式?

2024-06-24 11:48:33 发布

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

我有一个短信样本“花卢比300.00在商店名称从卡号xx2123”。这就像假设任何银行短信你收到手机后,你的交易。你知道吗

我需要用python编写一个健壮的程序。你知道吗

我想到了下面的解决方案,只考虑给定的字符串。你知道吗

def split_string(samplestring):
    list_string = samplestring.split(' ')
    return list_string


if __name__ == '__main__':
    samplestring = 'Spent Rs 300.00 at Shop Name from card number XXXX2123'

    list_string = split_string(samplestring)
    #print(list_string)

    print("Spent/Added:" + list_string[0])
    #print(list_string[0])

    print("Amount Type:"+ list_string[1])
    #print(list_string[1])

    print("Amount:"+ list_string[2])
    #print(list_string[2])

    print("Location where used:" + list_string[4] + list_string[5])
    #print(list_string[4] + list_string[5])

    print("Card Number:" + list_string[9])
    #print(list_string[9])

输出应如下所示:

Spent/Added:Spent
Amount Type:Rs
Amount:300.00
Location where used:ShopName
Card Number:XXXX2123

但这在以下情况下不起作用: 1如果商店名称为single workd或消息中有任何额外字符,则此操作无效 2它也不会与不同类型的SMS从不同的银行工作


Tags: 名称addedstringtype银行amount短信list
2条回答

以下代码适用于示例SMS:

import re
def split_str(s):
    print('Spent/Added:',re.sub('.*(Spent|Added).*', '\\1', s))
    print('Amount Type:', re.sub('.*?\s+?([a-zA-Z\W]+)\s+?[0-9]+.*', '\\1', s))
    print('Amount:',re.sub('.*?[A-Za-z\W]+(.*?)\sat.*', '\\1', s))
    print('Location where used:',re.sub('.*?at\s+(.*?)\s+from.*', '\\1', s))
    print('Card Number:',re.sub('.*?((X{4})([0-9]{4})).*?', '\\1', s))
    print('Full Card Number:',re.sub('.*?(([0-9]{4})\s+([0-9]{4})\s+([0-9]{4})\s+([0-9]{4})).*?', '\\1', s))

示例1:

s = 'Spent Rs 300.00 at Shop Name from card number XXXX2123'
split_str(s)

结果:

Spent/Added: Spent
Amount Type: Rs
Amount: 300.00
Location where used: Shop Name
Card Number: XXXX2123
Full Card Number: Spent Rs 300.00 at Shop Name from card number XXXX2123

示例2:

s = 'Spent $ 3 000 000 000.78 at Bgees & Inc. from card number 1111 2222 3333 4444'
split_str(s)

结果:

Spent/Added: Spent
Amount Type: $
Amount: 3 000 000 000.78
Location where used: Bgees & Inc.
Card Number: Spent $ 3 000 000 000.78 at Bgees & Inc. from card number 1111 2222 3333 4444
Full Card Number: 1111 2222 3333 4444

您正在尝试将机器生成的短文本消息解析为特定值。你知道吗

您可以尝试创建一个正则表达式列表,当您发现新的消息格式时,这些正则表达式会随着时间的推移而积累起来。当您收到一条消息时,请尝试使用每个正则表达式对其进行解析,直到有一个正则表达式匹配为止。如果没有匹配项,则创建一个警报以供稍后查看,以便可以创建新的正则表达式。你知道吗

您还可以将源电话号码映射到预期的正则表达式,但这可能只是一种优化,因为可能有您以前从未见过的来自同一银行的新电话号码。你知道吗

示例'Spent Rs 300.00 at Shop Name from card number XXXX2123'的正则表达式可能是:

r'Spent Rs (\d+)\.(\d\d) at (.*) from card number (\d+)'

相关问题 更多 >