【问题标题】:Map length of words in a sentence to a list of words将句子中单词的长度映射到单词列表
【发布时间】:2018-09-28 19:45:09
【问题描述】:

给出的指示要求返回字符串中每个单词的长度的代码。所以就像它会计算每个单词中的字母数量并将其打印在单词旁边 我有这个代码:

def word_lengths(a):
    a = a.lower()
    c = list(a)
    a = ""
    for x in c:
        if x == "," or x == "." or x == "'" or x == "!" or x == "?":
            c[c.index(x)] = ""
    for x in c:
        a += x
    y = a.split()
    z = {}
    for x in y:
        z[x] = len(x)
    return z
print(word_lengths("I ate a bowl of cereal out of a dog bowl today."))

返回:

{'dog': 3, 'bowl': 4, 'a': 1, 'out': 3, 'of': 2, 'ate': 3, 'cereal': 6, 'i': 1, 'today': 5}

【问题讨论】:

  • 你已经建立了一个反转你的结果的字典。

标签: python string python-3.x list dictionary


【解决方案1】:

您可以使用collections.defaultdict 获得 O(n) 解决方案:

from collections import defaultdict
from string import punctuation

def word_lengths(x):
    table = str.maketrans(punctuation, ' ' * len(punctuation))
    # alternatively, table = str.maketrans({key: None for key in punctuation})
    x = x.translate(table).lower()
    d = defaultdict(list)
    for word in x.split():
        d[len(word)].append(word)
    return d

res = word_lengths("I ate a bowl of cereal out of a dog bowl today.")

# defaultdict(list,
#             {1: ['i', 'a', 'a'],
#              2: ['of', 'of'],
#              3: ['ate', 'out', 'dog'],
#              4: ['bowl', 'bowl'],
#              5: ['today'],
#              6: ['cereal']})

说明

  • 首先删除标点符号(根据@Patrick's solution)并将字符串变为小写。
  • 初始化defaultdict 列表。
  • 按空格拆分列表、迭代单词并将元素附加到字典列表值中。

【讨论】:

  • 我会将您的 table = str.maketrans('', '', punctuation) 更改为 table = str.maketrans(punctuation, ' ' * len(punctuation))。这将替换为空格,因此由- 连接的单词不会被合并。
【解决方案2】:

可以简单地循环值以生成字典。

In [1]: c = defaultdict(list)

In [2]: for word in "I ate a bowl of cereal out of a dog bowl today.".split(' '):
...:     c[len(word)].append(word)
...:     

In [3]: c
Out[4]: 
defaultdict(list,
            {1: ['I', 'a', 'a'],
             2: ['of', 'of'],
             3: ['ate', 'out', 'dog'],
             4: ['bowl', 'bowl'],
             6: ['cereal', 'today.']})

【讨论】:

    【解决方案3】:

    您可以使用defaultdict 来做到这一点,它是标准库collections 模块中许多有用的数据结构之一。

    from collections import defaultdict
    import re
    
    def word_lengths(text):
        d = defaultdict(list)
        for word in re.findall(r'\w+', text.lower()):
            d[len(word)].append(word)
        return d
    

    我们使用re.findall 只匹配单词,没有空格和标点符号。如果您想包含连字符和撇号作为单词字符,您可以调整正则表达式。

    【讨论】:

      【解决方案4】:

      这是一个处理标点符号的版本,使用str.translate

      def word_lengths(s, remove='.,!?'):
          trans=str.maketrans('', '', remove)
          s = s.lower().translate(trans)
          d = defaultdict(list)
          for word in s.split():
              d[len(word)].append(word)
          return dict(d)  # Probably unnecessary and return d would work
      
      word_lengths("I ate a bowl of cereal out of a dog bowl today.")
      

      给我们

      {1: ['i', 'a', 'a'],
       2: ['of', 'of'],
       3: ['ate', 'out', 'dog'],
       4: ['bowl', 'bowl'],
       5: ['today'],
       6: ['cereal']}
      

      【讨论】:

        【解决方案5】:

        使用简单的迭代

        演示:

        def word_lengths(s):
            d = {}
            for i in s.split():           #Split by space
                l = len(i)
                if l not in d:            #Create len as key
                    d[l] = [i]
                else:
                    d[l].append(i)  
            return d
        
        
        print(word_lengths("I ate a bowl of cereal out of a dog bowl today."))
        

        输出:

        {1: ['I', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 6: ['cereal', 'today.']}
        

        【讨论】:

        • 谢谢!我确信所有其他 cmets 都是正确的,但这个解决方案对我来说最有意义,因为我到目前为止所学到的
        猜你喜欢
        • 2019-08-06
        • 2012-02-02
        • 2013-01-16
        • 2019-04-28
        • 1970-01-01
        • 2018-04-21
        • 1970-01-01
        • 2020-05-23
        • 1970-01-01
        相关资源
        最近更新 更多