首页 文章

Python代码,用于查找字符串中最短单词的总数 .

提问于
浏览
-2

我正在进行一项任务,我正在尝试为下面提到的问题编写代码 .

编写一个读取类型文本的python脚本,分析文本所包含的单词数量,并打印单词总数以及三个字母或更少的“短”单词数 .

给定的字符串是:“剧中的东西,我会 grab 国王的良心 . ”

这个问题有一个小技巧 . 一个人不能使用split()函数,因为它会将"I'll"视为一个单词,但是赋值要求我们将它视为两个不同的单词,因此给出一个输出,表明该字符串有14个单词 .

谈到“短语” . 它应该再次考虑“我将”作为两个单独的短字,它应该给出一个输出,表明该字符串有8个短字,即[“The”,“s”,“the”,“I”,“ll” ,“the”,“of”,“the”] .

非常感谢,如果你能分享这个问题的代码,我会很高兴 .

string= input("Enter string:")
word=1
y = 0
char = 0 
for i in string:
    if(i == ' ' or i == "'"):
        word = word+1
    for x in i:
        if len(x) <= 3:
           y = y+1

print("Number of words in the string:")
print(word)
print (y)

这是我的代码,输出如下:

Number of words in the string:
16
69

5 回答

  • 0

    您可以先用“”替换“”“,然后在结果字符串上调用split .

    >>> s = "The play's the thing wherein I'll catch the conscience of the king."
    >>> s = s.replace("'", " ")
    >>> s = s.split()
    >>> len(s)
    14
    >>> s
    ['The', 'play', 's', 'the', 'thing', 'wherein', 'I', 'll', 'catch', 'the', 'conscience', 'of', 'the', 'king.']
    
  • 0

    您可以使用 re.split() 拆分多个分隔符:

    import re
    
    s = "The play 's the thing wherein I'll catch the conscience of the king"
    
    lst = re.split(r"'| ", s)
    
    all_words_lst = [x for x in lst if x]
    print(f'Total words count: {len(all_words_lst)}')
    
    short_words_lst = [x for x in lst if x and len(x) <= 3]
    print(f'Total short words count: {len(short_words_lst)}')
    
    # Total words count: 14
    # Total short words count: 8
    
  • 0
    x = "The play 's the thing wherein I'll catch the conscience of the king."
    x = x.replace("'", " ")
    x = x.split()
    # Find all the words that have length less than 3
    ans = [i for i in x if len(i) <= 3]
    print("Total number of words {}, short words{}".format(len(x), len(ans)))
    
  • 1

    您可以将所有字符更改为空格 . 然后split()不带任何参数返回所有单词的列表 .

    string= input("Enter string:")
    word=0
    y = 0
    
    for i in range(len(string)):
        if string[i] == "\'":
            string[i] = ' '
    for i in string.split():
        word += 1
        if len(i) <= 3:
            y += 1
    
    print("Number of words in the string:")
    print(word)
    print (y)
    
  • 0

    使用 re.split 函数:

    import re
    
    input_string = input("Enter string:")  # for ex. "He is a good-hearted person, too"
    words = re.findall(r"\w+(?:-\w+)?", input_string)
    
    print("Total number of words:", len(words))
    print("Number of 'short' words:", len([w for w in words if len(w) <= 3]))
    

    输出:

    Total number of words: 6
    Number of 'short' words: 4
    

相关问题