【问题标题】:Using regex to constrain list of tuples使用正则表达式约束元组列表
【发布时间】:2017-09-09 17:19:16
【问题描述】:

给定一个单词元组列表及其句子中的词性:

[('We', 'PRP'),
 ('took', 'VBD'),
 ('advantage', 'NN'),
 ('of', 'IN'),
 ('the', 'DT'),
 ('half', 'JJ'),
 ('price', 'NN'),
 ('sushi', 'NN'),
 ('deal', 'NN'),
 ('on', 'IN'),
 ('saturday', 'NN')]

我想使用正则表达式提取具有特定 PoS 序列的术语。这类似于('JJ')*('NN')+,所以我有一个[('advantage', 'half price sushi deal', 'saturday')] 的列表。考虑到我将做数百个句子,执行这样一项任务的最合适的方式是什么?

谢谢!

【问题讨论】:

  • 你尝试过哪些方法?
  • @EugeneLisitsky 好吧,我认为正则表达式在这里没有意义,相反我应该使用元组索引编写一组条件

标签: python regex list tuples


【解决方案1】:

我认为这可能会奏效:

a = [('We', 'PRP'),
 ('took', 'VBD'),
 ('advantage', 'NN'),
 ('of', 'IN'),
 ('the', 'DT'),
 ('half', 'JJ'),
 ('price', 'NN'),
 ('sushi', 'NN'),
 ('deal', 'NN'),
 ('on', 'IN'),
 ('saturday', 'NN')]

b = iter(a[1:])

my_list = []
inner_list = []
accepted = ['JJ', 'NN']

for item in a:
    word = item[0]
    check = item[1]
    try:
        against = next(b)
        if check in accepted:
            if against[1] not in accepted:
                inner_list.append(word)
                my_list.append(inner_list)
                inner_list = []
            else:
                inner_list.append(word)
    except StopIteration:
        if check in accepted:
             inner_list.append(word)
             my_list.append(inner_list)
final = [' '.join(item) for item in my_list]

【讨论】:

  • 这是一个很好的解决方案!只需要确保候选术语或短语包含名词('NN'),因此将尝试修改代码
猜你喜欢
  • 2020-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多