简体   繁体   English

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

[英]How to intersect dictionary key (that is a text file) and print the value from the key that generated more intersections

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: 您可以使用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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM