我需要一些帮助找到一个单词的长度和有多少单词有这个长度的表格。例如,如果句子是"我要买一辆新自行车",
输出将是
文字长度 | 文字长度 | 1 | 1 |
---|---|
3 | 2 |
1 |
如果您希望不进行任何导入:
def wordlenghtsgrouper(phrase):
l = [len(w) for w in phrase.replace('.','').replace(',','').split()]
return {i:l.count(i) for i in l}
它返回一个字典,其中包含"length "以及每次出现的计数。
如果你不介意导入,你可以使用计数器,它专门做你要求的事情:
from collections import Counter
...
def wordlenghtsgrouper(phrase):
return Counter([len(w) for w in phrase.replace('.','').replace(',','').split()])
下面的代码首先去掉所有的标点符号,然后将句子拆分为一个单词列表,然后创建一个包含长度和计数的字典,最后在不导入任何内容的情况下以表格格式打印输出。
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