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

删除重复的单词,但在句子中保留重复的数字

  •  0
  • Chris  · 技术社区  · 7 年前

    我试图弄清楚如何删除重复的单词和句子,但不删除单个或两个数字。

    我以前使用以下方法删除重复项,同时保留顺序,但这会删除单个重复编号。

    df['reporting_name'] = df['reporting_name'].str.split().apply(lambda x: OrderedDict.fromkeys(x).keys() if x is not None else None).str.join(' ')
    

    所以我想我需要一些regex来拆分单词后面跟数字(包括空格),比如 this . 或者可能还有另一个通用的解决方案。

    输入

    "East Zone Mbc26 East Zone 1 2nd S11B Smds Smoke Damper 1 Status"
    "GF Command Room 1 Unit 1 Flow Temperature Temperature"
    

    预期产量

    "East Zone Mbc26 Zone 1 2nd S11B Smds Smoke Damper 1 Status"
    "GF Command Room 1 Unit 1 Flow Temperature"
    

    删除重复的单词,保留数字,保持单词顺序。

    当一个词有一个标识符并且是重复的,例如“区域1”,那么保留“区域”和“区域1”。

    1 回复  |  直到 7 年前
        1
  •  1
  •   sknat    7 年前

    如果你想保持每个非数字单词的第一次出现,这应该可以做到。你总是可以欺骗条件,迫使有最多两位数字。

    def cleanup(s):
        words = set()
        for (word, nextword) in zip(s.split(), s.split()[1:] + [None]):
            if word.isdigit():
                yield word
                continue
            if not word in words:
                words.add(word)
                yield word
            elif nextword and nextword.isdigit():
                yield word
    
    
    print ' '.join(cleanup("East Zone Mbc26 East Zone 1 2nd S11B Smds Smoke Damper 1 Status"))
    print ' '.join(cleanup("GF Command Room 1 Unit 1 Flow Temperature Temperature"))
    

    产量

    East Zone Mbc26 Zone 1 2nd S11B Smds Smoke Damper 1 Status
    GF Command Room 1 Unit 1 Flow Temperature