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