Spaces:
Runtime error
Runtime error
File size: 2,847 Bytes
0117cec |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
import json
from collections import defaultdict
from src.RemoteDatabase import RemoteDatabase
class Founder:
def __init__(self, filepath='datas/founder.jsonl'):
self.filepath = filepath
self.datas = {}
self.founder2items = defaultdict(list)
self.remote = RemoteDatabase()
try:
# self.load_founder()
pass
except FileNotFoundError:
self.datas = {}
# Initialize the reverse mapping
for word, founder in self.datas.items():
self.founder2items[founder].append(word)
def load_founder(self):
"""Load founder data from a jsonl file."""
with open(self.filepath, 'r', encoding='utf-8') as file:
for line in file:
data = json.loads(line.strip())
self.datas.update(data)
def save_founder(self):
"""Save founder data to a jsonl file."""
with open(self.filepath, 'w', encoding='utf-8') as file:
for word, founder in self.datas.items():
file.write(json.dumps({word: founder}, ensure_ascii=False) + '\n')
def get_founder(self, word):
return self.remote.get_top_founders(word=word)
def set_founder(self, word, founder, enforce=False):
"""Set the founder of a word if it's not already set or if enforce is True."""
self.remote.set_founders(word=word, founder=founder, enforce=enforce)
'''
if word in self.datas and not enforce:
print(f"Warning: {word} already has a founder: {self.datas[word]}. Use enforce=True to override.")
else:
self.datas[word] = founder
self.founder2items[founder].append(word)
self.save_founder()
'''
def get_all_items_from_founder(self, founder):
"""Get all words discovered by a specific founder."""
return self.founder2items.get(founder, [])
def get_top_rank(self, top_k=20):
return self.remote.get_top_founders(top_k=top_k)
'''
"""Get the top_k founders with the most discovered words."""
sorted_founders = sorted(self.founder2items.items(), key=lambda x: len(x[1]), reverse=True)
return sorted_founders[:top_k]
'''
# Example usage:
# founder = Founder()
# founder.set_founder('apple', 'Alice')
# founder.set_founder('banana', 'Bob')
# print(founder.get_founder('apple'))
# print(founder.get_all_items_from_founder('Alice'))
# print(founder.get_top_rank())
if __name__ == '__main__':
founder = Founder()
founder.set_founder('test_apple', '鲁鲁道祖')
founder.set_founder('test_banana', '鲁鲁道祖')
founder.set_founder('test_orange', "文钊道祖")
print(founder.get_founder('test_apple'))
print(founder.get_all_items_from_founder('Alice'))
print(founder.get_top_rank()) |