【问题标题】:Create dictionary with unique elements in list and their collocation使用列表中的唯一元素及其搭配创建字典
【发布时间】:2021-02-25 10:52:29
【问题描述】:

我需要以下方面的帮助:

  • 我想创建一个函数,当插入一个字符串时,我会得到一个字典,其中列表中的唯一元素作为键,并将其前后的文本作为值。 例如使用以下字符串:

我想拥有以下:

重要的是要注意,例如某些单词 a 重复并且旁边有不同的值。

我正在尝试以下功能:

def ffg(txt):
    txt = re.sub(r'[^\w\s]','',txt).lower().split()
    words = list(set(txt))
    indx = [words.index(i) for i in txt] 
    
    
    for x in range(len(txt)):
        res = txt[x]

但正如你所见,它根本不起作用。

【问题讨论】:

    标签: python list dictionary


    【解决方案1】:

    我假设您已经过了一系列单词,因此请随意将文本拆分为单词。

    from collections import defaultdict
    
    def word_context(l):
        context = defaultdict(set)
        for i, w in enumerate(l):
            if i + 1 < len(l):
                context[w].add(l[i+1])
            if i - 1 >= 0:
                context[w].add(l[i-1])
        return dict(context)
    

    结果:

    >>> l
    ['half', 'a', 'league', 'half', 'a', 'league', 'half', 'a', 'league', 'onward', 'all', 'in', 'the', 'valley', 'of', 'death', 'rode', 'the', 'six', 'hundred']
    >>> word_context(l)
    {'half': {'a', 'league'}, 'a': {'half', 'league'}, 'league': {'half', 'a', 'onward'}, 'onward': {'all', 'league'}, 'all': {'onward', 'in'}, 'in': {'all', 'the'}, 'the': {'six', 'rode', 'in', 'valley'}, 'valley': {'the', 'of'}, 'of': {'death', 'valley'}, 'death': {'rode', 'of'}, 'rode': {'death', 'the'}, 'six': {'the', 'hundred'}, 'hundred': {'six'}}
    

    【讨论】:

      【解决方案2】:

      另一种变化:

      import re
      
      def collocate(txt):
          txt = re.sub(r'[^\w\s]', '', txt).lower().split()
      
          neighbors={}
      
          for i in range(len(txt)):
              if txt[i] not in neighbors:
                  neighbors[txt[i]]=set()
      
              if i>0:
                  neighbors[txt[i]].add(txt[i-1])
      
              if i < len(txt) - 1:
                  neighbors[txt[i]].add(txt[i+1])
      
          return neighbors
      
      print(collocate("Half a league, half a league, Half a league onward, All in the valley of Death Rode the six hundred."))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-09-13
        • 1970-01-01
        • 2014-01-28
        • 1970-01-01
        • 1970-01-01
        • 2014-02-10
        • 1970-01-01
        相关资源
        最近更新 更多