如何与字典键(即文本文件)相交并从生成更多交叉点的键中打印值

时间:2014-03-23 04:44:40

标签: python dictionary

如何与字典键(即文本文件)相交并从生成最长列表的键中打印值?这是我到目前为止所得到的。我的问题是在代码的最后。

#define intersection between user text input and my file inputs
def me_and_the_plant(m, p):
    return list(set(m) & set(p))

#get user text input
words = raw_input("Say anything that comes to your mind: ")
print
input_words = words.split()

#define valid user input
if len(input_words) < 3:
    print "I need more than that."
    Mithras()
else:
    me = input_words

#make dictionary with my input files
songs = {"Wicked.txt" : "Wicked.wav",
         "Requiem.txt" : "Requiem.wav"}

#use text files as keys
for lyrics in songs.keys():
    f = open(lyrics)
    r = f.read()
    the_plant = r.split()
    #for the key that gets the most intersections, print its value
    print me_and_the_plant(me, the_plant)

1 个答案:

答案 0 :(得分:0)

更改最后的循环以找出哪一个最多:

    ...
#use text files as keys
most_intersection_key = None
most_intersection = None
most_intersection_len = 0
me = me.split()
for lyrics in songs:
    with open(lyrics) as f:
        the_plant = f.read().split()
    intersection = me_and_the_plant(me, the_plant)
    intersection_len = len(intersection)
    if intersection_len > most_intersection_len:  # most seen?
        most_intersection_key = lyrics
        most_intersection_len = intersection_len
        most_intersection = intersection

if most_intersection_key:
    print most_intersection_key, most_intersection_len, most_intersection
else:
    print 'there were no intersections'

您可以使用collections.Counter类稍微简化它并删除一行me_and_the_plant()函数:

    ...
from collections import Counter

intersection_lengths = Counter()
intersections = {}
me = me.split()
for song_filename in songs:
    with open(song_filename) as f:
        lyrics = f.read().split()
    intersections[song_filename] = set(me) & set(lyrics)
    intersection_lengths[song_filename] = len(intersections[song_filename])

most_intersections = intersection_lengths.most_common(1)
if most_intersections:
    print most_intersections[0], most_intersections[1], \
          list(intersections[most_intersections[0]])
else:
    print 'there were no intersections'