[英]python - return dict object with str as key and no.of times it occurs as value
get_last_three_letters_dict()
函数将传递文本字符串作为参数。 该函数首先将参数字符串转换为小写,然后返回具有以下内容的字典对象:
remove_less_than_2
代码将删除结果字典中的所有对,其中最后三个字母仅在文本的参数字符串中出现一次。
键是长度大于2的文本参数字符串中任何单词的最后三个字母,以及
对应的值,即文本参数字符串中以最后三个字母结尾的单词数。
到目前为止,我有:
sentence = 'west best worst first tapping snapping in a pest the straining singing forest living'
def remove_less_than_2(a_dict):
all_keys = list(a_dict.keys())
for key in all_keys:
if a_dict[key] == 1:
del a_dict[key]
def get_last_three_letters_dict(sentence):
new_dict = {}
new_sentence = sentence.lower()
new_sentence = sentence.split()
for word in new_sentence:
if len(word) > 2:
new_dict[word[-3:]] = sentence.count(word[-3:])
return new_dict
但是它返回的某些值超出了应有的值。
est : 4
ing : 6
rst : 2
我究竟做错了什么?
sentence = ' "west best worst first tapping snapping in a pest the straining singing forest living'
# Get the last 3 letters of each word if its length is greater than 3
words_gt3 = [word[-3:] for word in sentence.split() if len(word) >= 3]
# Count them (you can use collections.Counter() too)
out = {}
for w in words_gt3:
if w not in out.keys():
out[w] = 0
out[w] += 1
# Filter non repeated words
out = dict([e for e in out.items() if e[1] > 1])
print out
# {'rst': 2, 'est': 4, 'ing': 5}
我究竟做错了什么?
sentence.count()
:计算整个字符串(而不是每个单词)中出现的次数。 因此'singing'.count('ing')
将返回2
。 这就是为什么你算6
ing
而不是5
。
您想通过dict / list理解和计数器轻松实现的目标:
from collections import Counter
sentence = ' "west best worst first tapping snapping in a pest the straining singing forest living'
filtered_counter = {k: v for k, v in Counter([word[-3:] for word in sentence.lower().split() if len(word) > 2]).items() if v > 1}
首先,我们从标准库中导入Counter
类型,然后定义sentence
。 下一行是在降低整个句子并检查单词长度是否至少为3之后,使用每个单词的最后3个字母创建一个数组。 它正在从中创建一个Counter对象,这产生了一个类似dict
的对象,该对象枚举了在数组中找到元素的次数; 然后使用dict理解来过滤输出,以使其不包含非重复的单词。
我将分解这种单线格式,以便您可以更好地看到它:
lowered_sentence = sentence.lower()
words = lowered_sentence.split()
filtered_words = [word for word in words if len(word) > 2]
# filtered_words = filter(lambda x: len(x) > 2, words)
word_ends = [word[-3:] for word in filtered_words]
counter = Counter(word_ends)
filtered_counter = {key: value for key, value in counter.items() if value > 1}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.