Python中的字符串模式检测

2024-06-02 10:39:08 发布

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

我有一个用字符串描述的操作列表,例如“BPxPyPzPC”,其中每个字母代表一个操作,C代表一个事件。在

一些用户的操作(例如“B”、“Px”、“Py”和“Pz”)导致了一个事件(在我的示例中,字母“C”),其他用户没有,所以我想确定最常导致事件的操作模式(例如“BPxPyPz”),在Python中什么是最有效的方法?在

谢谢!在

示例代码:

c=['' for x in range(0,4)]
c[0]="BPxPxPyPC"
c[1]="BPxPyPyPC"
c[2]="BPyPxPyPC"
c[3]="BPyPxPyPC"

#do something

#desired result
The most likely sequence of actions to achieve "C" is "BPyPxPy"

Tags: 方法字符串用户py示例列表字母模式
2条回答

我会这样做(只考虑事件ev中具有最大点击量的第一个操作序列:

def checkSeq(c, stack):
    stackSeqs = [x[0] for x in stack]

    if c not in stackSeqs:
        stack.append([c,0])
    else:
        idx = stackSeqs.index(c)
        stack[idx][1] += 1
    return stack

def max_act_ev(ev, stack):
    acts=[]
    for row in stack:
        if ev in row[0][-1]:
            acts.append(row)
    if len(acts) > 0:
        res = sorted(acts, key=lambda x: x[1],reverse=True)
        return res[0]
    else:
        return []


# Start of code

stack=[["BPyPxPyPC",1],["BPxPxPyPC",1],["BPxPxPxPC",1]]
c = "BPxPxPyPC"
ev = "C"

stack = checkSeq(c,stack)
seq = max_act_ev(ev,stack)

print(stack)
if len(seq)>0:
    print('The most likely sequence of actions to achieve "'+seq[0][-1]+'" is "'+seq[0][:-1]+'"')
else:
    print("No actions found for event "+ev)

目前还不清楚你是否以及如何区分这些行为。在

我使用正则表达式匹配后跟C的任何字符串,并使用Counter来获得最常见的字符串。在

以下是获得结果的最简单方法:

import re
from collections import Counter

c = ["BPxPxPyPC", "BPxPyPyPC", "BPyPxPyPC", "BPyPxPyPC"]

cnt = Counter()
for sequence in c:
    m = re.match('^(.*)C$', sequence)
    if m: cnt.update([m.group(1)])

print('The most likely sequence is " {}"'.format(cnt.most_common(1)[0][0]))
# BPyPxPyP

相关问题 更多 >