【问题标题】:How do I count the number of words beginning with a letter?如何计算以字母开头的单词数?
【发布时间】:2023-02-21 11:24:30
【问题描述】:

您好,我需要帮助计算给定 book_excerpt 中以字母“a”开头的单词数量,我们存储在 num_with_a 和“d”中,我们存储在 num_with_d 中。

book_excerpt = "It was both the greatest and worst of times; it was the Age of Wisdom and the Age of Folly; it was the Epoch of Belief and the Epoch of Skepticism; it was the Age of Light and the Age of Darkness; it was the Spring of Hope and the Winter of Despair."

这是我试过的:

num_with_a = for f in book_excerpt:
   
    if beginning 'a' in f:

      print(f)

num_with_d = for f in book_excerpt:
    
    if beginning 'd' in f:
       
      print(f)

【问题讨论】:

标签: python


【解决方案1】:

您可以使用 for 循环:

for i in words:
    if list(i)[0] == "a":
        count += 1

count 是以字母开头的单词数。 words 是单词列表。您可以通过以下方式获得words

book_excerpt = "It was both the greatest and worst of times; it was the Age of Wisdom and the Age of Folly; it was the Epoch of Belief and the Epoch of Skepticism; it was the Age of Light and the Age of Darkness; it was the Spring of Hope and the Winter of Despair."

words = book_excerpt.split(" ")

【讨论】:

    猜你喜欢
    • 2018-09-03
    • 2014-01-02
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2016-01-13
    • 2022-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多