Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/108.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
查找字符串中单词的长度,并查找有多少单词具有该长度。不使用导入和NLTK(Python)_Python_String_List_Function_Dictionary - Fatal编程技术网

查找字符串中单词的长度,并查找有多少单词具有该长度。不使用导入和NLTK(Python)

查找字符串中单词的长度,并查找有多少单词具有该长度。不使用导入和NLTK(Python),python,string,list,function,dictionary,Python,String,List,Function,Dictionary,我需要一些帮助,找出一个单词的长度和有多少个单词的长度与表格。例如,如果句子是“我要买一辆新自行车” 输出将是 字长 这个长度的课文有多少个单词 1. 1. 3. 2. 4. 1. 如果您更喜欢在没有任何导入的情况下进行此操作: def wordlenghtsgrouper(phrase): l = [len(w) for w in phrase.replace('.','').replace(',','').split()] return {i:l.count(i) for i

我需要一些帮助,找出一个单词的长度和有多少个单词的长度与表格。例如,如果句子是“我要买一辆新自行车”

输出将是

字长 这个长度的课文有多少个单词 1. 1. 3. 2. 4. 1.
如果您更喜欢在没有任何导入的情况下进行此操作:

def wordlenghtsgrouper(phrase):
    l = [len(w) for w in phrase.replace('.','').replace(',','').split()]
    return {i:l.count(i) for i in l}
它返回一个包含“长度”和每次出现次数的字典

如果您不介意导入,您可以使用计数器,它专门满足您的要求:

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

我只是写了一些类似的东西。好的。第二行第二列怎么样。当只有2个单词的长度为3时。不是应该是1吗?