Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 是否使用文件中的下一个单词更新词典值?_String_Python 3.x_Dictionary - Fatal编程技术网

String 是否使用文件中的下一个单词更新词典值?

String 是否使用文件中的下一个单词更新词典值?,string,python-3.x,dictionary,String,Python 3.x,Dictionary,我想读取一个文件并创建一个字典,每个单词作为关键字,后面的单词作为值 例如,如果我有一个包含以下内容的文件: 'Cake is cake okay.' 创建的词典应包含: {'cake': ['is', 'okay'], 'is': ['cake'], 'okay': []} 到目前为止,我已经设法用我的代码做了相反的事情。我已经用文件中的上一个单词更新了字典值。我不太确定如何改变它,以使其按预期工作 def create_dict(file): word_dict = {}

我想读取一个文件并创建一个字典,每个单词作为关键字,后面的单词作为值

例如,如果我有一个包含以下内容的文件:

'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
对于较短的解决方案,您可以使用和:

import io
from itertools import zip_longest  # izip_longest in Python 2
import string

def create_dict(fobj):
    word_dict = {}
    punc = string.punctuation
    for line in fobj:
        clean_words = [word.strip(punc) for word in line.lower().split()]
        for word, next_word in zip_longest(clean_words, clean_words[1:]):
            words = word_dict.setdefault(word, [])
            if next_word is not None:
                words.append(next_word)
    return word_dict
测试它:

>>> fobj = io.StringIO("""Cake is cake okay.""")
>>> create_dict(fobj)
{'cake': ['is', 'okay'], 'is': ['cake'], 'okay': []}

将从给定文件生成单词的代码(空格拆分、大小写折叠、标点符号剥离等)与创建二元词典的代码(本问题的主题)分开:

看。为了在一个文件中支持少于两个单词,代码需要稍作调整。如果需要确切的类型,可以在此处调用
return dict(bigrams)
。例如:

>>> create_bigram_dict('cake is cake okay'.split())
defaultdict(list, {'cake': ['is', 'okay'], 'is': ['cake']}
要从文件创建dict,可以定义
get\u words(文件)

用法:
create\u bigram\u dict(获取单词(打开('filename'))


。代码可能会在单词内保留标点符号,例如:

>>> import regex as re
>>> re.fullmatch(r'\p{P}*(.*?)\p{P}*', "doesn't.").group(1)
"doesn't"
注意:末尾的点已消失,但内部保留了
。要删除所有标点符号,可以使用:

>>> re.sub(r'\p{P}+', '', "doesn't.")
'doesnt'
注意:单引号也不见了

>>> import regex as re
>>> re.fullmatch(r'\p{P}*(.*?)\p{P}*', "doesn't.").group(1)
"doesn't"
>>> re.sub(r'\p{P}+', '', "doesn't.")
'doesnt'