字符串python中的模式查找

字符串python中的模式查找,python,pattern-matching,Python,Pattern Matching,我尝试创建一个修改的LZW,它将在字符串中查找单词的模式。我的问题是,如果第一个元素在列表中,则不检查最后一个元素。我在这里看到了伪代码:。以下是我的压缩脚本: string = 'this is a test a test this is pokemon' diction = [] x = "" count = 0 for c in string.split(): print (c) print (x) #x = x + " " + c if

我尝试创建一个修改的LZW,它将在字符串中查找单词的模式。我的问题是,如果第一个元素在列表中,则不检查最后一个元素。我在这里看到了伪代码:。以下是我的压缩脚本:

string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string.split():
      print (c)
      print (x)
      #x = x + " " + c 
      if x in diction:
            x += " " + c
            #print("debug")
      else:
            #print(x)
            diction.append(x)
            x = c
            count +=1
            #print(count)

print (diction)
我试图通过在字符串末尾“添加”一个随机单词来解决第二个问题,但我认为这不是最好的解决方案


对于第一个问题,我试图将变量x定义为str或None,但我在列表中得到了这个

链接处理字符,拆分字符串将得到一个单词数组。 以便在字典中获取非空字符串并解析最后一个元素

string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string.split():
      print (c)
      if x+" "+c in diction:
            x += " " + c
      else:
            diction.append(x+" "+c)
            x = c
            count +=1

print (diction)
但也许你会喜欢这样的东西:

string = 'this is a test a test this is pokemon'
diction = []
x = ""
count = 0
for c in string:
      print (c)
      if x+c in diction:
            x += c
      else:
            diction.append(x+c)
            x = c
            count +=1

print (diction)

我不确定代码假装什么,但为了解决您提到的问题,我认为您可以这样做:

string = 'this is a test a test this is pokemon'
diction = []
x = None
count = 0
for c in string.split():
    if x in diction:
        x += " " + c
    else:
        if x: diction.append(x)
        x = c
        count += 1

if not x in diction: diction.append(x)

print (diction)
该代码的输出为:

['this', 'is', 'a', 'test', 'a test', 'this is', 'pokemon']