两个不同的结构化python列表之间的匹配

时间:2016-05-16 11:06:51

标签: python list python-2.7 match

我使用python 2.7,我有2个列表,其中一个是这种形状:

t1 = [('go', 'VB'), [('like', 'IN'), [('i', 'PR')]], [('to', 'TO')], [('there', 'RB')]]

另一个是以这种格式存储的文本文件:

t2 = [go:VB, [like:IN, [i:PR]], [to:TO], [there:RB]]

我想看看(t1)是否匹配(t2)。

我面临的一个问题是文本文件中没有('')所以它们看起来像变量。

你能帮忙找到一种方法来匹配这两者。

def match(t1, t2):
    #check here if the nested lists match or not.   
    return True

我试图将(t1)转换为字符串并删除' ('和')'用一个空的'替换它们。 然后替换' ,'用' :'但它给出了很多引号,我认为这不是解决这个问题的好主意。

3 个答案:

答案 0 :(得分:2)

这个答案没有使用static final int CAM_REQUEST = 1; button = (Button) findViewById(R.id.button); imageView = (ImageView) findViewById(R.id.imageView); Button button2 = (Button) findViewById(R.id.button3); button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { Intent camera_intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); File file = getFile(); camera_intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file)); startActivityForResult(camera_intent , CAM_REQUEST); } }); button2.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { String path = "sdcard/camera_app/cam_image.jpg"; imageView.setImageDrawable(Drawable.createFromPath(path)); } }); @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String path = "sdcard/camera_app/cam_image.jpg"; imageView.setImageDrawable(Drawable.createFromPath(path)); } 这是一个非常不安全的事情。

  1. 使用eval()将您的str转换为字符串。
  2. 借助t1
  3. 删除t1t1中的所有空格
  4. 使用rereplace转换sub
  5. 最后,比较字符串
  6. t2

    修改

    如果您想支持标签页和换行符,则需要执行此操作

    ### 1
    t1 = str(t1)
    
    ### 2
    t1 = t1.replace(" ", "")
    t2 = t2.replace(" ", "")
    
    ### 3
    t2 = re.sub(r"(\w+):(\w+)", r"('\1','\2')", t2)
    
    ### 4
    print(t1 == t2)
    

答案 1 :(得分:1)

一种天真而简单的方法 - 使用regex substitution将字符串从文件转换为Python可评估的形式,然后使用邪恶的eval

import re

s2 = '[go:VB, [like:IN, [i:PR]], [to:TO], [there:RB]]'

# 'go:VB' -> '("go", "VB")'
s2_pyth = re.sub(r'(\w+):(\w+)', r'("\1", "\2")', s2)
# '[("go", "VB"), [("like", "IN"), [("i", "PR")]], [("to", "TO")], [("there", "RB")]]'

l2 = eval(s2_pyth)
# [('go', 'VB'), [('like', 'IN'), [('i', 'PR')]], [('to', 'TO')], [('there', 'RB')]]

if l1 == l2:
    # or whatever more specific comparison

我认为,在这种背景下使用eval(似乎是无害的学术NLP任务)是可以的。如果文本文件中的标记不是严格的字母数字,那么您可能需要更智能的正则表达式r'\w+'来匹配它们,也许是......比如r'[^\[\]]+' ...

答案 2 :(得分:1)

假设您的结构仅由包含两个字符串的列表和元组组成,则以下函数应该通过递归生成目标字符串来执行您所要求的操作:

def format_list(l):
  res = "["
  items = []
  for item in l:
    if isinstance(item,list):
      items.append(format_list(item))
    elif isinstance(item,tuple):
      items.append(item[0] + ':' + item[1])
  res += ", ".join(items) + "]"
  return res