【问题标题】:Finding the Length of a Word in a String and Finding How Many Words Have That Length. Without Using Import And NLTK(Python)查找字符串中单词的长度并查找有多少单词具有该长度。不使用 Import 和 NLTK(Python)
【发布时间】:2021-04-27 12:46:46
【问题描述】:

我需要一些帮助来查找单词的长度以及有多少单词具有表格的长度。例如,如果句子是“我要买一辆新自行车。”,

输出将是

Length of Word How Many Words In The Text In This Length
1 1
3 2
4 1

【问题讨论】:

  • 第二行第二列2。当只有2个长度为3的单词时。不应该是1吗?

标签: python string list function dictionary


【解决方案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

【讨论】:

    【解决方案2】:

    如果您更喜欢完全不使用任何导入:

    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()])
    

    【讨论】:

    • 只是在写类似的东西。这样就可以了。
    猜你喜欢
    • 2013-11-01
    • 2015-05-21
    • 2015-12-28
    • 1970-01-01
    • 2016-05-28
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多