python - 如何将输出值转换为字典

标签 python dictionary

Text = '''《权力的游戏》是一部由大卫·贝尼奥夫和 D. B. Weiss 创作的美国奇幻电视剧 为HBO。该节目是在贝尔法斯特其他地方制作和拍摄的 英国。'''

import re
new_text = ''
punctuations = '''!.,'''
for character in Text:
    if character not in punctuations:
        new_text = new_text + character
from collections import Counter
split_text = Text.split(' ')
count = Counter(split_text)
most_freq_word_new = [key for key,valu in count.items() if valu == max(count.values())]
for index, word in enumerate(split_text):
    for i in most_freq_word_new:
        if word == i:
            print (word)
            #print (index)
            suffix_word =  split_text[index + 1]
            prefix_word =  split_text[index - 1]
            print (suffix_word)
            print (prefix_word)

我的输出

and
D
Benioff
and
filmed
produced
in
Belfast
filmed
in
the
elsewhere

我想要的输出

{and:['D','Benioff','filmed','produced'],
in:['Belfast','filmed','the','elsewhere']}

最佳答案

这是一种使用dict的方法。

演示:

Text = '''Game of Thrones is an American fantasy drama television series created by David Benioff and D. B. Weiss for HBO. The show was both produced and filmed in Belfast elsewhere in the United Kingdom.'''
import re
new_text = ''
punctuations = '''!.,'''
for character in Text:
    if character not in punctuations:
        new_text = new_text + character
from collections import Counter, defaultdict
split_text = Text.split(' ')
count = Counter(split_text)
most_freq_word_new = [key for key,valu in count.items() if valu == max(count.values())]

result =  {i: [] for i in most_freq_word_new}     #Create Dict with word as key and list as value
for index, word in enumerate(split_text):
    for i in most_freq_word_new:
        if word == i:
            #print (index)
            suffix_word =  split_text[index + 1]
            prefix_word =  split_text[index - 1]
            result[word].extend([suffix_word, prefix_word])  #Use list.extend to add to result. 
print(result)

输出:

{'and': ['D.', 'Benioff', 'filmed', 'produced'],
 'in': ['Belfast', 'filmed', 'the', 'elsewhere']}

关于python - 如何将输出值转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57184244/

相关文章:

python - 当我在脚本中使用 __name__ 变量时出现运行时警告

使用 Guava 将 Java Map<String, String> 映射到 List<String>

java - 确保密码不包含字典单词

python - 从字典列表中返回一个特定的字典

Python Bigram 字典格式

python - functools partial 是如何做到的?

python - 在Linux上编译的Python源代码

Python:从不同模块登录到同一文件的正确方法

python:使用回车和逗号打印不起作用

java - 在Java中可以更改映射中的值