Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.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
如何编写一个Python程序来读取文本文件,并构建一个映射每个单词的字典_Python_List_Python 2.7_Dictionary - Fatal编程技术网

如何编写一个Python程序来读取文本文件,并构建一个映射每个单词的字典

如何编写一个Python程序来读取文本文件,并构建一个映射每个单词的字典,python,list,python-2.7,dictionary,Python,List,Python 2.7,Dictionary,我很难编写一个Python程序来读取文本文件,并构建一个字典,将文件中出现的每个单词映射到文件中紧跟该单词之后的所有单词的列表。单词列表可以是任何顺序,并且应该包括重复的单词 例如,键”和“可能有一个列表[“then”,“best”,“after”,…]列出了文本中和“之后的所有单词 任何想法都会大有帮助 有几个想法: 为输出设置集合.defaultdict。这是一个字典,其中包含尚未存在的键的默认值(在本例中,如aelfric5578所示,是一个空的列表) 按顺序建立文件中所有单词的列表;及

我很难编写一个Python程序来读取文本文件,并构建一个字典,将文件中出现的每个单词映射到文件中紧跟该单词之后的所有单词的列表。单词列表可以是任何顺序,并且应该包括重复的单词

例如,键
”和“
可能有一个列表
[“then”,“best”,“after”,…]
列出了文本中
和“
之后的所有单词

任何想法都会大有帮助

有几个想法:

  • 为输出设置
    集合.defaultdict
    。这是一个字典,其中包含尚未存在的键的默认值(在本例中,如aelfric5578所示,是一个空的
    列表
  • 按顺序建立文件中所有单词的列表;及
  • 您可以使用
    zip(lst,lst[1:])
    创建连续的列表元素对 这就是我要做的:

    from collections import defaultdict
    
    # My example line :
    s = 'In the face of ambiguity refuse the temptation to guess'
    
    # Previous string is quite easy to tokenize but in real world, you'll have to :
    # Remove comma, dot, etc...
    # Probably encode to ascii (unidecode 3rd party module can be helpful)
    # You'll also probably want to normalize case
    
    lst = s.lower().split(' ')  # naive tokenizer
    
    ddic = defaultdict(list)
    
    for word1, word2 in zip(lst, lst[1:]):
        ddic[word1].append(word2)
    
    # ddic contains what you want (but is a defaultdict)
    # if you want to work with "classical" dictionnary, just cast it :
    # (Often it's not needed)
    dic = dict(ddic)
    

    抱歉,如果我似乎窃取了评论员的想法,但这几乎与我在一些项目中使用的代码相同(类似的文档算法预计算)

    欢迎访问stackoverflow.com

    你确定你需要一本字典吗?
    如果文本很长,只需对多个条目重复几次相同的数据,就会占用大量内存。
    而如果你使用一个函数,它会随意给你想要的列表。 例如:

    s = """In Newtonian physics, free fall is any motion
    of a body where its weight is the only force acting
    upon it. In the context of general relativity where
    gravitation is reduced to a space-time curvature,
    a body in free fall has no force acting on it and
    it moves along a geodesic. The present article
    concerns itself with free fall in the Newtonian domain."""
    
    import re
    
    def say_me(word,li=re.split('\s+',s)):
        for i,w in enumerate(li):
            if w==word:
                print '\n%s at index %d followed by\n%s' % (w,i,li[i+1:])
    
    say_me('free')
    
    结果

    free at index 3 followed by
    ['fall', 'is', 'any', 'motion', 'of', 'a', 'body', 'where', 'its', 'weight', 'is', 'the', 'only', 'force', 'acting', 'upon', 'it.', 'In', 'the', 'context', 'of', 'general', 'relativity', 'where', 'gravitation', 'is', 'reduced', 'to', 'a', 'space-time', 'curvature,', 'a', 'body', 'in', 'free', 'fall', 'has', 'no', 'force', 'acting', 'on', 'it', 'and', 'it', 'moves', 'along', 'a', 'geodesic.', 'The', 'present', 'article', 'concerns', 'itself', 'with', 'free', 'fall', 'in', 'the', 'Newtonian', 'domain.']
    
    free at index 38 followed by
    ['fall', 'has', 'no', 'force', 'acting', 'on', 'it', 'and', 'it', 'moves', 'along', 'a', 'geodesic.', 'The', 'present', 'article', 'concerns', 'itself', 'with', 'free', 'fall', 'in', 'the', 'Newtonian', 'domain.']
    
    free at index 58 followed by
    ['fall', 'in', 'the', 'Newtonian', 'domain.']
    
    赋值
    li=re.split('\s+',s)
    是将参数
    li
    绑定到作为参数传递的对象
    re.split('\s+',s)
    的一种方式。

    此绑定只执行一次:解释器读取函数定义以创建函数对象时。它是一个用默认参数定义的参数。

    使用
    defaultdict(list)
    应该可以让您到达您想要去的地方,假设您知道如何读取文件并遍历每一行。如果你有更具体的问题,请修改你的问题。“卡住了,我什么都没有”-真的吗?什么都没有?如果您从某个地方开始(编写可以解析您的文件的代码),您的问题将更加具体和具体。非常感谢。我赞成你的问题,虽然没有什么特别的。但这是为了鼓励蟒蛇!