词根匹配
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'))