silk-road's picture
Upload 23 files
0117cec verified
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())