首页 > 解决方案 > 如何计算列表中包含特定字母的单词数量?

问题描述

我正在使用 Python 3。我正在寻找一种方法让 Python 遍历列表中的所有单词,并计算其中包含字母“e”的单词数量。我不想计算“e”出现的数量,只计算有一个或多个出现的单词的数量。

例如:

你好,你好,是否

我希望程序给出数字 2(因为列表中有两个项目包含“e”)

这是我没有工作的代码(我必须从单词列表中计数):

# defines the text to use
text = "Hello. My name is Elijah Beetle."
lettertocount = "e"

# specifies what punctuation to remove from text
punc = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# removes the punctuation from text
for present in text:
    if present in punc:
        text = text.replace(present,"")

listofwords = text.split()

print(listofwords)

countofletter = 0

for counting in listofwords:
    if counting in lettertocount:
        countofletter += 1

print(countofletter)

标签: python

解决方案


这是一个解决方案:

def e_words(words):
  e_count = 0
  for i in words:
    if "e" in i:
      e_count += 1
  return e_count
print(e_words(["Hello", "Hi", "Whether"]))

该代码创建了一个名为e_wordsthat 的函数,该函数遍历列表并在单词中找到“e”时将其words添加到变量中。e_count


推荐阅读