标签:set max 首字母 算法 collections 哈希 sen 词根
词根匹配
import collections
def replacewords(dict, sentence):
d = collections.defaultdict(set) # 默认的字典类型 值的类型为set类型
s = collections.defaultdict(int) # 默认的字段类型 值的类型是int类型
sen = sentence.split() # 句子的列表
for w in dict:
w_0 = w[0] # 词根的首字母
d[w_0].add(w) # 添加到集合中 首字母的开头字母作为键 词根为值(集合, 可以有多个) 存入
s[w_0] = max(s[w_0], len(w)) # 所有词根中的最大长度
for i, w in enumerate(sen): # 带索引的列表
for j in range(s[w[0]]): # 根据 句子的首字母(在s中存在的) 取 相关词根的最大长度
if w[:j+1] in d[w[0]]: # 遍历词根 集合中首字母的值 rat {'rat'}
sen[i] = w[:j+1]
break
return ' '.join(sen)
def replacewords1(dict, sens):
# 创建两个字典
# 用来存储词根 单词首字母: 词根 集合可以存多个
# 词根首字母:所有词根最长的长度
d_set = collections.defaultdict(set)
d_max = collections.defaultdict(int)
sen_li = sens.split()
for w in dict:
w_0 = w[0]
d_set[w_0].add(w)
d_max[w_0] = max(d_max[w_0], len(w))
for i, w in enumerate(sen_li):
w_0 = w[0]
for j in range(d_max[w_0]):
if w[:j+1] in d_set[w_0]:
sen_li[i] = w[:j+1]
break
return ' '.join(sen_li)
print(replacewords(['cat', 'bat', 'rat', 'cttttt'], 'the cale was rattled by the battery ctttttdsf'))
print(replacewords1(['cat', 'bat', 'rat', 'cttttt'], 'the cale was rattled by the battery ctttttdsf'))
标签:set,max,首字母,算法,collections,哈希,sen,词根 来源: https://blog.csdn.net/qq_42684307/article/details/90812585
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。