【发布时间】:2018-07-15 18:09:12
【问题描述】:
我想为从文本文件中读取的字符串生成 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']
【问题讨论】:
-
请给出示例输入和预期输出
-
而重复的“字符串”是指重复的行重复一行中的单词吗?
-
@pylang 抱歉,添加了输入/输出。我的意思是重复的文本条目。
-
再次查看您的输出。您缺少
321并且您的 id 与您的重复项相同。您提到了再添加两个字符。
标签: python list uniqueidentifier