简体   繁体   中英

Tuple of lists to a dictionary? Character names as keys and the amount of paragraphs they have as values

dialogue = (['Benvolio','Part, fools!\nPut up your swords; you know not what you do.'], 
            ['Tybalt', 'What, art thou drawn among these heartless hinds?\nTurn thee, Benvolio, look upon thy death.'],
            ['Benvolio', 'I do but keep the peace: put up thy sword,\nOr manage it to part these men with me.'],
            ['Tybalt', 'What, drawn, and talk of peace! I hate the word,\nAs I hate hell, all Montagues, and thee:\nHave at thee, coward!\n[They fight]\n[Enter, several of both houses, who join the fray;]\nthen enter Citizens, with clubs]'])

dialogue contains the whole play of Shakespeare (I've only included the first 4 lines)

output should be:

{"Character name":number of occurrences of each character}

so for my example^ it should say

{"Benvolio": 2, "Tybalt": 2}  # as each character appears 2 times

I am trying to count the number of times a character speaks. I am not interested in what's inside their specific dialogue. In my example, Benvolio speaks twice and Tybalt speaks twice hence both of their values in the dictionary being 2. I don't understand how to use counter() to iterate over my tuple. I understand how to count if there is one list but how do I count the character names in all of the lists in the tuple? Thanks

collections.Counter will count the occurrences of a hashable item in a sequence. In your case, you want the first value in each list. This can be done with generator that selects that value.

from collections import Counter

dialogue = (['Benvolio','Part, fools!\nPut up your swords; you know not what you do.'],
            ['Tybalt', 'What, art thou drawn among these heartless hinds?\nTurn thee, Benvolio, look upon thy death.'],
            ['Benvolio', 'I do but keep the peace: put up thy sword,\nOr manage it to part these men with me.'],
            ['Tybalt', 'What, drawn, and talk of peace! I hate the word,\nAs I hate hell, all Montagues, and thee:\nHave at thee, coward!\n[They fight]\n[Enter, several of both houses, who join the fray;]\nthen enter Citizens, with clubs]'])

occurances = Counter(occurance[0] for occurance in dialogue)
print(occurances)

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.

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