【问题标题】:Remove duplicate word sentence删除重复的单词句子
【发布时间】:2016-12-14 03:16:53
【问题描述】:

我有一个句子列表。

我想处理这样的重复:

  • 白鞋女
  • 女鞋白色
  • 女款小白鞋

我想变成这样:

  • 白鞋女

我可以在 Notepad++ 中执行此操作吗?

或者其他一些软件?

【问题讨论】:

  • 您的全套要求是什么?如何定义重复?大写字母和小写字母起什么作用?您如何选择保留哪些“重复”以及丢弃哪些?
  • 我怎么说呢,就像示例 3 行一样,有重复的单词,但位置不同。所以我想保留第一个出现,并丢弃具有相同单词的其他行。大写和小写都不需要。
  • 不需要是什么意思?那我们忽略大小写?那么无论输入如何,输出都可以是“white shoes women”或“WHITE SHOES WOMEN”吗?
  • 是的,我的意思是这样,忽略大小写
  • 优秀。那么接下来返回遇到的第一句话至关重要吗?还是返回一个包含所有单词的句子就足够了。 “鞋子白人女性”会是可接受的输出吗?

标签: duplicates notepad++ programmatically-created programmatically


【解决方案1】:

我不认为你可以在 Npp 中做这样的工作。

这是一种使用 perl 完成工作的方法,它保持第一行的大小写和顺序。
(感谢@jwpfox 提供输入示例)。

use Modern::Perl;

my $prev = '';
while(<DATA>) {
    chomp;
    my $str = join'',sort split' ',lc$_;
    say $_ if $str ne $prev;
    $prev = $str;
}

__DATA__
White shoes women
Shoes women white
Women white shoes
White shoes women
Shoes women white
Women white shoes
Men black boots
Black boots men
Boots men black
girl yellow shirt
yellow girl shirt
pants blue boy

输出:

White shoes women
Men black boots
girl yellow shirt
pants blue boy

PHP 版本:

$s = array(
'White shoes women',
'Shoes women white',
'Women white shoes',
'White shoes women',
'Shoes women white',
'Women white shoes',
'Men black boots',
'Black boots men',
'Boots men black',
'girl yellow shirt',
'yellow girl shirt',
'pants blue boy');

$prev = '';
foreach($s as $line) {
    $list = explode(' ', strtolower($line));
    sort($list);
    $str = implode('',$list);
    if ($str != $prev) echo $line,"\n";
    $prev = $str;
}

输出:

White shoes women
Men black boots
girl yellow shirt
pants blue boy

【讨论】:

  • 谢谢你的人,但如果在 php 中这样做可能吗?我对 perl 不熟悉。
  • @prajaprihana:我添加了一个 PHP 版本,请参阅我的编辑。
  • 太棒了!谢谢!!
【解决方案2】:

使用“其他软件”选项。

input.txt 文件内容:

White shoes women
Shoes women white
Women white shoes
Men black boots
Black boots men
Boots men black
girl yellow shirt
yellow girl shirt
pants blue boy

Python 3:

sentences = []

with open('input.txt', mode='r') as infile:
    for line in infile:
        wordlist = line.split(' ')
        words = []
        for word in wordlist:
            word = word.strip()
            words.append(word.lower())

        words.sort()

        if words not in sentences:
            sentences.append(words)

with open('output.txt', mode='w') as outfile:
    for sentence in sentences:
        for word in sentence:
            outfile.write(word + ' ')
        outfile.write('\n')

output.txt 文件内容:

shoes white women 
black boots men 
girl shirt yellow 
blue boy pants 

【讨论】:

  • 太棒了!非常感谢。这就是我想做的。但是有没有简单的教程来执行它,我不熟悉phyton。或者,如果在 php 中这样做,这可能吗?我真的很感谢你的帮助。再次感谢。
  • 我对 PHP 无能为力,抱歉。如果你想安装 Python 来运行上面的代码,那么这里有一个指向指令python.org/downloads 的链接。看起来 Perl 选项更符合您的口味,100% 没问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 1970-01-01
  • 1970-01-01
  • 2017-06-20
  • 1970-01-01
  • 2019-07-30
相关资源
最近更新 更多