我正在搜索一个python代码,它可以找到字符串中最短单词的总数 . 例如,如果字符串是“剧中的东西,我会 grab 国王的良心 . ”那么结果应该是“8个简短的单词”
input_string = "The play 's the thing wherein I'll catch the conscience of the king."
要计算单词数:print(len(input_string.split()))
print(len(input_string.split()))
输出:13
13
要计算三个字母或更少的字数:print(len([x for x in input_string.split() if len(x) <= 3]))
print(len([x for x in input_string.split() if len(x) <= 3]))
输出:6
6
如果您想要只有三个字母或更少字母的单词列表,请排除len()函数 .print([x for x in input_string.split() if len(x) <= 3])
print([x for x in input_string.split() if len(x) <= 3])
输出:['The', "'s", 'the', 'the', 'of', 'the']
['The', "'s", 'the', 'the', 'of', 'the']
1 回答
input_string = "The play 's the thing wherein I'll catch the conscience of the king."
要计算单词数:
print(len(input_string.split()))
输出:
13
要计算三个字母或更少的字数:
print(len([x for x in input_string.split() if len(x) <= 3]))
输出:
6
如果您想要只有三个字母或更少字母的单词列表,请排除len()函数 .
print([x for x in input_string.split() if len(x) <= 3])
输出:
['The', "'s", 'the', 'the', 'of', 'the']