【发布时间】:2016-03-03 12:27:00
【问题描述】:
我想读取一个文件并创建一个字典,其中每个单词作为键,后面的单词作为值。
例如,如果我有一个文件包含:
'Cake is cake okay.'
创建的字典应包含:
{'cake': ['is', 'okay'], 'is': ['cake'], 'okay': []}
到目前为止,我已经设法对我的代码做相反的事情。我已经用文件中的前一个单词更新了字典值。我不太确定如何更改它以使其按预期工作。
def create_dict(file):
word_dict = {}
prev_word = ''
for line in file:
for word in line.lower().split():
clean_word = word.strip(string.punctuation)
if clean_word not in word_dict:
word_dict[clean_word] = []
word_dict[clean_word].append(prev_word)
prev_word = clean_word
提前感谢大家的帮助!
编辑
更新进度:
def create_dict(file):
word_dict = {}
next_word = ''
for line in file:
formatted_line = line.lower().split()
for word in formatted_line:
clean_word = word.strip(string.punctuation)
if next_word != '':
if next_word not in word_dict:
word_dict[next_word] = []
if clean_word == '':
clean_word.
next_word = clean_word
return word_dict
【问题讨论】:
标签: string python-3.x dictionary