How can I intersect a dictionary key (that is a text file) and print the value from the key that generated the longest list? This is what I got so far. My question is at the end of the code.
#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)
Change the loop at the end to figure out which one has the most:
...
#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'
You could simplify it slightly using the collections.Counter
class and getting rid of the one line me_and_the_plant()
function:
...
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'
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.