[英]Generate unique IDs for a list of strings with duplicates
我想為從文本文件中讀取的字符串生成 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']
如果字符串是重復的,我希望字符串的第一個實例具有包含 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()
將鍵與每個唯一的行相關聯。 然后我們從鍵中切出所需的序列。 另請參閱有關從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']
您的問題有點令人困惑,我不明白生成 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']]}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.