【问题标题】:python logic to extract pattern of strings in listpython逻辑提取列表中的字符串模式
【发布时间】:2021-03-04 07:22:15
【问题描述】:
text =  [('Automated', 'PROPN'), ('Unit', 'PROPN'), ('testing', 'NOUN'), ('design', 'NOUN'), ('and', 'CCONJ'), ('implementation', 'NOUN'), ('experience', 'NOUN')]

pattern  =['NOUN', 'CCONJ', 'NOUN', 'NOUN']

#program应该提取=>>>>设计和实现经验 #可以使用正则表达式或列表方法或字符串方法来完成

'''
def get_matched(text,patterns):   # patterns => list of cases
    punctuations = ''',-''' 
    s = ""
    for char in text:
      if char not in punctuations:
          s = s + char
    if "/" in s :     # replacing "/"  with or because "/" is recognised as symbol in pos tags
      s = s.replace('/', ' or ')
    res = re.sub(' +', ' ', s)        
    doc = nlp(res)
    words = []
    for case in patterns:
          matcher = Matcher(nlp.vocab) 
          matcher.add("matching_1",[case[1::]]) 
          matches = matcher(doc) 
          for match_id,start,end in matches:
                span = doc[start:end]
                l =  span.text.split()
                if len(l)  > 0 :
                  #print(l)
                  index =  case[0]
                  try:
                    for i in range (len(index)):
                      temp = ""
                      for ind in index[i]:
                          temp =  temp  + l[ind] + " "
                      words.append(temp)
                    words.append(' '.join(l),text)
                    print("->>>>>>>>>>>",text)
                  except:
                    print(case,l)
                    
    return words

'''
  1. 我用 sapcy 匹配完成了它,但我必须为它编写逻辑

【问题讨论】:

  • 看起来像一个家庭作业问题。请发表您为解决此问题所做的真正努力。
  • 不,实际上这是我的 nlp 案例之一,等等让我评论整个准备工作

标签: python list loops conditional-statements logic


【解决方案1】:
temp = ""
for i in pos_tags:
        temp =  temp  +i 
for i in cases: 
    case  = ''.join(i[0])
    if temp.find(case) > 0:
        case_lenght = len(i[0])
        for ind in range(len(pos_tags)-(case_lenght-1)):
            if pos_tags[ind:(case_lenght+ind)] == i[0]:
                extracted_sent = text[ind:ind+case_lenght]
                for tuple in i[1]:
                    word = ""
                    for index in tuple:
                        word =  word + " " + text[index]
                    print(word)

        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-05
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 2018-12-13
    相关资源
    最近更新 更多