簡體   English   中英

Python。 我如何制作一個更大列表的小部分列表?

[英]Python. How do I make a list of small portions of a bigger list?

for word in list6:
    if word = "TRUMP":

所以,我有一個辯論記錄中每個單詞的列表。 當特朗普說話時,它以“TRUMP”開頭。 我需要把他的話放在一個單獨的列表中。 如果 list6 中的單詞是“TRUMP”,那么我需要將所有內容放入一個列表中,直到它說出另一個人的名字。 他不止一次講。

我只需要幫助完成這個循環。

list6 = ['TRUMP','I','am','good', 'HILLARY','I','am','good','too','TRUMP','But','How?']
person_words = {'TRUMP':[], 'HILLARY':[]}

person_names = person_words.keys()

one_person_onetime_words = []

for word in list6:
    if word in person_names:
        if len(one_person_onetime_words):
            person_words[this_person].append(one_person_onetime_words)
            one_person_onetime_words = []
        this_person = word
    else:
        one_person_onetime_words.append(word)

person_words[this_person].append(one_person_onetime_words)

print person_words

{'HILLARY': [['I', 'am', 'good', 'too']], 'TRUMP': [['I', 'am', 'good'], ['But', 'How?']]}

所以,這一次就給出了所有人的所有不同的談話。

正如您在對問題的評論中所提到的,如果您只想獲得一個人的話,您可以使用以下內容:

from copy import copy

list6 = ['TRUMP','I','am','good', 'HILLARY','I','am','good','too','TRUMP','But','How?']
person_words = []
all_persons = ['TRUMP', 'HILLARY']
person_looking_for = 'TRUMP'

filter_out_persons = copy(all_persons)
filter_out_persons.remove(person_looking_for)

person_onetime_words = []

capture_words = False
for word in list6:
    if word == person_looking_for:
        capture_words = True
        if len(person_onetime_words):
            person_words.append(person_onetime_words)
            person_onetime_words = []
    elif word not in filter_out_persons and capture_words:
        person_onetime_words.append(word)
    else:
        capture_words = False

person_words.append(person_onetime_words)
print "{}'s words".format(person_looking_for)
print person_words

那給

TRUMP's words
[['I', 'am', 'good'], ['But', 'How?']]

並且,下面將給出一個以單詞為鍵的字典,值將再次是一個字典,每個人對該單詞的頻率。

import pprint

list6 = ['TRUMP','I','am','good', 'HILLARY','I','am','good','too','TRUMP','But','How?']

person_names = ['TRUMP','HILLARY']

word_frequency = {}
for word in list6:
    if word in person_names:
        person = word
    else:
        word = word.lower()
        if word in word_frequency:
            if person in word_frequency[word]:
                word_frequency[word][person] += 1
            else:
                word_frequency[word][person] = 1
        else:
            word_frequency[word] = {person: 1}

pprint.pprint(word_frequency)

{'am': {'HILLARY': 1, 'TRUMP': 1},
 'but': {'TRUMP': 1},
 'good': {'HILLARY': 1, 'TRUMP': 1},
 'how?': {'TRUMP': 1},
 'i': {'HILLARY': 1, 'TRUMP': 1},
 'too': {'HILLARY': 1}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM