python - 将句子中的单词长度映射到单词列表

标签 python string python-3.x list dictionary

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

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}

最佳答案

您可以将 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
  • 按空格拆分您的列表,迭代单词并将元素附加到您的字典列表值。

关于python - 将句子中的单词长度映射到单词列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49901863/

相关文章:

string - 为什么从标准输入读取用户输入时我的字符串不匹配?

java - 如何正确格式化结果集的输出

python-3.x - 如何拒绝负数作为 Argparse 模块中的参数

python - 如何通过 Python 计算 Linux 上具有特定标题的窗口的数量?

JavaScript:Unicode 空格字符

django - 休伊;不在一个 Django 应用程序中运行任务

python - 尝试调用未定义的函数 glutInit

Worker 和 Driver 中的 Python 版本不同

python - 如何在 django 的 python 中将日期时间转换为字符串

python - OSMNX - 边缘的 "part"被认为是最近的