为具有重复项的字符串列表生成唯一ID

时间:2018-02-05 19:34:23

标签: python list uniqueidentifier

我想为正在从文本文件中读取的字符串生成ID。如果字符串是重复的,我希望字符串的第一个实例具有包含6个字符的ID。对于该字符串的重复项,我希望ID与原始ID相同,但另外两个字符。我遇到了逻辑问题。这是我到目前为止所做的:

from itertools import groupby
import uuid
f = open('test.txt', 'r')
addresses = f.readlines()

list_of_addresses = ['Address']
list_of_ids = ['ID']


for x in addresses:
    list_of_addresses.append(x)


def find_duplicates():

    for x, y in groupby(sorted(list_of_addresses)):
        id = str(uuid.uuid4().get_hex().upper()[0:6])
        j = len(list(y))
        if j > 1:
            print str(j) + " instances of " + x
            list_of_ids.append(id)
        print list_of_ids

find_duplicates()

我该如何处理?

编辑:这是test.txt的内容:

123 Test
123 Test
123 Test
321 Test
567 Test
567 Test

输出:

3 occurences of 123 Test

['ID', 'C10DD8']
['ID', 'C10DD8']
2 occurences of 567 Test

['ID', 'C10DD8', '595C5E']
['ID', 'C10DD8', '595C5E']

2 个答案:

答案 0 :(得分:1)

  

如果字符串是重复的,我希望字符串的第一个实例具有包含6个字符的ID。对于该字符串的重复项,我希望ID与原始ID相同,但另外两个字符。

尝试使用collections.defaultdict

<强>鉴于

import ctypes
import collections as ct


filename = "test.txt"


def read_file(fname):
    """Read lines from a file."""
    with open(fname, "r") as f:
        for line in f:
            yield line.strip()

<强>代码

dd = ct.defaultdict(list)
for x in read_file(filename):
    key = str(ctypes.c_size_t(hash(x)).value)      # make positive hashes
    if key[:6] not in dd:
        dd[key[:6]].append(x)
    else:
        dd[key[:8]].append(x)

dd

输出

defaultdict(list,
            {'133259': ['123 Test'],
             '13325942': ['123 Test', '123 Test'],
             '210763': ['567 Test'],
             '21076377': ['567 Test'],
             '240895': ['321 Test']})

生成的字典具有每个第一次出现的唯一行的键(长度为6)。对于每个连续的复制行,将为该键切割两个附加字符。

您可以根据需要实施密钥。在这种情况下,我们使用hash()将密钥与每个唯一行相关联。然后我们从密钥中切割出所需的序列。另见关于制作positive hash values from ctypes的帖子。

要检查结果,请从defaultdict

创建相应的查找词典
# Lookups 
occurrences = ct.defaultdict(int)
ids = ct.defaultdict(list)

for k, v in dd.items():
    key = v[0]
    occurrences[key] += len(v)
    ids[key].append(k)

# View data
for k, v in occurrences.items():
    print("{} instances of {}".format(v, k))
    print("IDs:", ids[k])
    print()

输出

1 instances of 321 Test
IDs: ['240895']

2 instances of 567 Test
IDs: ['21076377', '210763']

3 instances of 123 Test
IDs: ['13325942', '133259']

答案 1 :(得分:0)

你的问题有点令人困惑,我不知道生成id的标准是什么,这里我只是向你展示逻辑不精确的解决方案,你可以从逻辑中获取帮助

track={}
with open('file.txt') as f:
    for line_no,line in enumerate(f):
        if line.split()[0] not in track:
            track[line.split()[0]]=[['ID','your_unique_id']]
        else:
            #here put your logic what you want to append if id is dublicate
            track[line.split()[0]].append(['ID','dublicate_id'+str(line_no)])

print(track)

输出:

{'123': [['ID', 'your_unique_id'], ['ID', 'dublicate_id1'], ['ID', 'dublicate_id2']], '321': [['ID', 'your_unique_id']], '567': [['ID', 'your_unique_id'], ['ID', 'dublicate_id5']]}