我需要一些帮助来查找单词的长度以及用表格显示有多少个单词的长度。例如,如果句子是“我将购买一辆新自行车”,
输出将是
字长 | 在此长度的文本中有多少个单词 |
---|---|
1个 | 1个 |
3 | 2 |
4 | 1个 |
下面的代码首先删除所有标点符号,然后将句子分成单词列表,然后创建长度和计数的字典,最后以表格格式打印输出,而无需导入任何内容。
sentence = "I will' buy; a new bike."
#remove punctuation marks
punctuations = ['.', ',', ';', ':', '?', '!', '-', '"', "'"]
for p in punctuations:
sentence = sentence.replace(p, "")
#split into list of words
word_list = sentence.split()
#create a dictionary of lengths and counts
dic = {}
for word in word_list:
if len(word) not in dic:
dic[len(word)] = 1
else:
dic[len(word)] += 1
#write the dictionary as a table without importing anything (e.g.Pandas)
print('Length of word | Count of words of that length')
for length, count in dic.items():
print('------------------------------------------')
print(f' {length} | {count}')
#Output:
#Length of word | Count of words of that length
#------------------------------------------
# 1 | 2
#------------------------------------------
# 4 | 2
#------------------------------------------
# 3 | 2
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句