python - 如何将输出值转换为字典
问题描述
Text = '''《权力的游戏》是大卫·贝尼奥夫和 DB 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']}
推荐阅读
- spring - Ehcache 两次注册 bean
- office-ui-fabric - 带有 Fluent UI 的 Pivot 的粘性标签栏
- laravel - 使用分页数据时 Livewire 抛出错误
- python - 具有窗口大小的滚动平均值和列值的间隔
- python - 使用 matplotlib 从 excel 生成图形
- c++ - 分段错误推回共享内存中的向量
- sql - 根据两列组合中的数据删除行数据
- c# - 如果数据存在(来自循环)C#,如何写入下一行 CSV
- javascript - 我可以通过 Ajax 响应在不同的域上设置 cookie 吗?
- c++ - 如何使用我的函数类删除动态数组?