7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「Pythonで重複してる文を削除するプログラム」をやってみた

Last updated at Posted at 2014-12-16

元ネタ: Pythonで重複してる文を削除するプログラム

こういうのどう?とコメントしようと思ったらコード書いた方が分かりやすいなと思って書いてみた。

  • 重複チェックにハッシュ値を使う
  • with 文をまとめて読み書きした方が効率的
  • 何行目が重複しているかを出力
check.py
# -*- coding: utf-8 -*-
import sys
from hashlib import sha256
from os.path import isfile


def output_unique_text(path, enc='utf-8'):
    d = {}
    with open(path, 'rb') as reader, open('output.txt', 'wb') as writer:
        for i, line in enumerate(reader, 1):
            value = sha256(line).hexdigest()
            if d.get(value):
                msg = '{}: "{}" is duplicate.\n'
                decoded = line.decode(enc).strip()
                sys.stdout.buffer.write(bytes(msg.format(i, decoded), enc))
            else:
                d[value] = line
                writer.write(line)


def main():
    if len(sys.argv) <= 1 or not isfile(sys.argv[1]):
        print('specify path/to/filename')
        sys.exit(1)
    output_unique_text(sys.argv[1])
    print('confirm output.txt')


if __name__ == '__main__':
    main()
7
7
6

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?