【问题标题】:count (how to find all letters, and count them)计数(如何找到所有字母,并计算它们)
【发布时间】:2022-11-11 06:30:45
【问题描述】:

如何制作 = 2(有两个“the”)

import re
text = "there are a lot of the cats"
o = re.findall("the", text)
print(o)


def text(word):
    count = 0
    for word in text:
        if "ou" in text:
            count += 1
    return count

print(count)

print(i)

此代码应返回 2(因为有 2 个“the”)

【问题讨论】:

  • 您可以使用简单的len(text) 获得字母计数,并且要获得每个字母,您可以编写一个简单的 for 循环 for letter in text: print(letter)
  • 你需要数字母或单词吗?
  • print(len(o)) 不是您要找的东西吗?

标签: python count


【解决方案1】:

@chris 是对的。您已在第 3 行和第 4 行成功执行此操作,但第 4 行将其返回到数组 ['the', 'the'] 中。在 python 中,您可以使用len(yourArrayHere) 获取数组/列表的“长度”(其中有多少东西)。

因此,如果您只想查看计数,可以执行以下操作:

print(len(o))

如果要将其保存到变量中, 在第 5 行,只需执行以下操作:

count = len(o)

之后的一切都不需要

【讨论】:

    【解决方案2】:

    如果您想获取所有单词并计算它们,这里是代码:

    text = input("Your text: ")
    words_in_text = {}
    for word in text.lower().split(" "):
        if word in words_in_text.keys():
            words_in_text[word] += 1
        else:
            words_in_text[word] = 1
    

    要获得多个单词,只需使用:

    word_to_get = input("Which word to check: ")
    print(words_in_text[word_to_get])
    

    这是所有单词的一个很好的打印格式:

    print("
    Word | Count")
    for word, count in words_in_text.items():
        print(f"{word}: {count}")
    

    输出:

    Your text: My name is Echo Echo
    
    Word | Count
    my: 1
    name: 1
    is: 1
    echo: 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-05
      • 1970-01-01
      • 1970-01-01
      • 2015-05-27
      • 2023-01-16
      • 2022-01-06
      • 2016-10-17
      • 2015-02-02
      相关资源
      最近更新 更多