【问题标题】:Merging two lists in python在python中合并两个列表
【发布时间】:2021-10-07 14:17:24
【问题描述】:

我有两个单词列表,一个包含来自文本的关键字(名词),另一个包含来自同一文本的所有 adj + 名词配对。我需要将列表合并为一个仅包含关键字名词和成对形容词的列表(如果有的话) 例如:

keywords:{apple, house, sword}
noun_adj:{red apple, fast car, big house, new phone, sharp sword}
result:{red apple, big house, sharp sword}

我是 python 新手,一直在寻找答案,但我不知道要搜索什么。 2 个列表是 output 和 noun_adj_pairs。

【问题讨论】:

    标签: python nlp


    【解决方案1】:

    假设这些是列表中的字符串...

    使用列表推导

    keywords = ['apple', 'house', 'sword']
    noun_adj = ['red apple', 'fast car', 'big house', 'new phone', 'sharp sword']
    
    result = [n for n in noun_adj for k in keywords if k in n]
    

    或者嵌套的for循环

    keywords = ['apple', 'house', 'sword']
    noun_adj = ['red apple', 'fast car', 'big house', 'new phone', 'sharp sword']
    
    result = []
    for n in noun_adj:
        for k in keywords:
            if k in n:
                result.append(n)
    

    根据 Corralien 的评论进行了编辑,谢谢。

    【讨论】:

    • 很好的答案。 +1,但将列表理解放在首位。它更 Pythonic。
    • 值得一提的是,内置函数'x in y'是基于字符而不是单词的。因此,当关键字是名词或形容词的一部分时,它将产生真值。例如,“好管家”的结果将为真。 (More information)
    【解决方案2】:

    我使用 split() 函数将形容词和名词分开。之后,只有名词通过 for 语句进行检查。

    result = set()
    for i in noun_adj:
        k = i.split()
        if k[1] in keyword: result.add(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多