我需要在 2 元素列表中输出一个包含字符数的列表,该列表给出了每个单词的字符数:
[['How', 3], ['are', 3], ['you', 3], ['today', 5]]
我正在使用一个函数
定义字符:
l = [] # list for holding your result
# convert string s into a list of 2-element-lists
s = text.split()
s = [[word ,len(word)] for word in s.split()]
print("Output:\n", s)
print()
return l
text = "How are you today"
l = char(text)
print()
但我得到的输出是计算每个单词的总字符数,而不是每个单词的特定字符数:
[['How', 17], ['are', 17], ['you', 17], ['today', 17]]
感谢任何帮助,谢谢。
最佳答案
你的问题是你在计算文本中的字符数,但你必须计算每个单词中的字符数。最后,您甚至可以将代码简化为:
def char(s):
return [[word ,len(word)] for word in s.split()]
然后你可以通过以下方式调用它:
text = "How are you today"
l = char(text)
print(l)
输出:
[['How', 3], ['are', 3], ['you', 3], ['today', 5]]
关于python - 从句子中输出一个列表并计算每个单词的字符数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42563166/