It’s not that it’s easy to pull. First write a rough version (the code is ugly and the order is completely ignored XD), and then slowly improve it:
char2id = {}
id2charset = {}
def getcharset(c):
try:
return id2charset[char2id[c]]
except:
return None
def newcharset(chars):
newset = set(chars)
return newset
def merge(charset1, charset2):
if id(charset1)==id(charset2):
return
charset1 |= charset
for c in charset2:
char2id[c] = id(charset1)
id2charset.pop(id(charset2))
with open('test2') as reader:
for line in reader:
chars = line.strip().split()
newset = newcharset(chars)
id2charset[id(newset)] =newset
for c in chars:
charset = getcharset(c)
if charset:
merge(newset, charset)
else:
char2id[c] = id(newset)
with open('report', 'w') as writer:
for id, charset in id2charset.items():
print(' '.join(charset), file=writer)
Information test:
A B
C A
D C
E F
N G
C N
X Y
F P
P Q
X Z
Result:
P E Q F
X Y Z
B D C G N A
It is recommended that the script you check should be written like this:
from collections import Counter
with open('report', 'r') as reader:
ct = Counter()
for line in reader:
ct += Counter(line.strip().split())
for item, count in ct.most_common():
if count <= 1:
break
print(item, count)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
result = {}
with open('5.1.txt', 'r') as f:
alist = []
blist = []
lines = f.readlines()
for line in lines:
line1 = line.strip().split()
for i in line1:
blist.append(i)
if i not in alist:
alist.append(i)
for a in alist:
print a, blist.count(a)
It’s not that it’s easy to pull. First write a rough version (the code is ugly and the order is completely ignored XD), and then slowly improve it:
Information
test
:Result:
It is recommended that the script you check should be written like this:
Questions I answered: Python-QA