Pythonで完全に重複する行を見つける方法は何ですか?

PythonのcollectionsモジュールのCounterを使用して、完全に同じ行を見つけることができます。まず、ファイルを開き、行ごとにファイル内容を読み込む必要があります。次に、各行をリストに追加し、Counterを使用して各行の出現回数を計算します。最後に、カウントが1よりも大きい行を見つけると、それらの行が完全に同じ行です。

以下はサンプルコードです。

from collections import Counter

def find_duplicate_lines(file_path):
    lines = []
    
    with open(file_path, 'r') as file:
        for line in file:
            lines.append(line.strip())
    
    duplicates = [line for line, count in Counter(lines).items() if count > 1]
    
    return duplicates

file_path = 'file.txt'  # 替换为你的文件路径
duplicate_lines = find_duplicate_lines(file_path)

if duplicate_lines:
    print('完全重复的行:')
    for line in duplicate_lines:
        print(line)
else:
    print('没有找到完全重复的行。')

上記のコードは、各行がテキスト行(文字列)であることを前提としており、空白文字を無視しています。他のタイプの行を考慮する必要がある場合や、空白文字を区別する必要がある場合は、コードを適宜変更してください。

bannerAds