代码之家  ›  专栏  ›  技术社区  ›  Merve

如果我想返回列表上的一个操作,但当它返回空值时它保持不变,我怎么说呢?

  •  1
  • Merve  · 技术社区  · 2 年前

    我有一个土耳其语词组列表。我想应用词干,我找到了turkishnlp包。虽然它有一些缺点,但它通常返回正确的单词。然而,当我把这个应用到列表中时,我不希望列表的结构改变,我希望他不知道的单词保持不变。

    例如,我有以下清单: mylist=['yolda','gelirken','kopek','grdm',['cok','tatl±yd±]]

    我写了这个函数:

    from trnlp import TrnlpWord
    def tr_stemming(x):
        obj = TrnlpWord()
        obj.setword(x) if isinstance(x, str) else type(x)(map(tr_stemming, x))
        return obj.get_stem if isinstance(x, str) else type(x)(map(tr_stemming, x))
    

    此函数返回以下列表:

    tr_stemming(mylist)
    

    [yol]、[gelir]、[gèr]、[tatlı]]

    但是,我想将其作为输出: [['yol'、'gelir'、'kopek'、'gÃr']、['cok'、'tatlı']

    如何更新我的功能? 谢谢你的帮助!

    1 回复  |  直到 2 年前
        1
  •  0
  •   mozway    2 年前

    IIUC,你可以修改你的函数:

    def tr_stemming(x):
        if isinstance(x, str):
            obj = TrnlpWord()
            obj.setword(x)
            stem = obj.get_stem
            return stem if stem else x
        elif isinstance(x, list):
            return [tr_stemming(e) for e in x]
        
    out = tr_stemming(mylist)
    

    输出:

    [['yol', 'gelir', 'kopek', 'gör'], ['cok', 'tatlı']]
    
    推荐文章