如何计算包含特定字母的列表中的单词数量?

2024-09-24 06:22:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Python3。我希望为Python创建一种方法来遍历列表中的所有单词,并计算其中有多少单词包含字母“e”。我不想数一数“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)

Tags: thetotextinfrom列表for数量
2条回答

num=(len([如果word.lower()中的letttocount为单词列表中的单词])

这里有一个解决方案:

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_words的函数,该函数遍历列表words,并在单词中找到“e”时添加到变量e_count

相关问题 更多 >