【问题标题】:How do I print the words on a list that do not have the letter 'e'?如何打印列表中没有字母“e”的单词?
【发布时间】:2025-12-19 10:15:06
【问题描述】:

代码必须打印列表中不包含字母 e 的单词。我正在使用的列表位于一个名为 words.txt 的单独文件中。我的代码中有一些漏洞,但我不确定它们在哪里,因为我得到的单词只包含字母 e。这是教科书 Think Python 中的练习 9.2。

第 2 到 6 行是读取一个单词的代码,如果它有 rhe 字母 e,则返回 True of False。然后我被要求修改它以完成任务。

fin = open('words.txt')
def has_no_e(word):
  if 'e' in word:
    return True
  else:
    return False
count = 0
for word in fin:
    word = word.strip()
    if has_no_e(word):
        count = +1
        print (word)
percent = (count / 113809.0) * 100
print(str(percent))

该代码应该打印 words.txt 上所有不包含字母 e 的单词。

【问题讨论】:

  • 如果'e' in word 为真,您的has_no_e 函数将返回True
  • has_no_e 可能太简单了,甚至无法成为一个函数;您只是在代码中增加了开销,并没有真正的好处,因为 if has_no_e(word): 并不比 if 'e' not in word: 更清晰。

标签: python python-3.6


【解决方案1】:

我希望这段代码是正确的

count = 0
fin   = open('words.txt', 'r') #Open the file for reading
words = fin.readlines()        #Read words from file
fin.close()                    #Close the file

for word in words:              
    word = word.strip()
    if not 'e' in word:        #If there is NO letter e in the word
        count = count + 1
        print(word)

percent = (count / 113809.0) * 100
print(str(percent))

通过做

if 'e' in word:
    return True
else:
    return False

您选择了每个带有字母“e”的单词,而不是没有它们的单词。

【讨论】:

  • 这很有帮助,非常感谢您的及时回复。
  • 不客气!:) 如果您还需要什么,请告诉我!
【解决方案2】:
def has_no_e(word):
  if 'e' in word:
    return True
  else:
    return False

这个函数的作用与它的名字相反。如果单词 DOES 有“e”,则返回 True

【讨论】:

    【解决方案3】:

    检查这在函数中是否有效。

    if 'e' in word:
        return False
    else:
        return True
    

    【讨论】:

      【解决方案4】:

      像这样:(前 10 个单词):

      filename = '/etc/dictionaries-common/words'
      words = [word for word in open(filename).read().split() 
               if 'e' not in word]
      print(words[:10])
      

      【讨论】:

        【解决方案5】:

        整个文件内容正在这里读入word。上面代码中的for循环应该修改为

        for word in fin:
        

        for word in fin.read().split():
        

        另外,如果 has_no_e() 应该在 word 不包含 e 时返回 True,那么它的实现应该有以下行:

            if 'e' in word:
        

        替换为

            if 'e' not in word:
        

        【讨论】:

          【解决方案6】:

          这就是我将单词放入列表后解决此问题的方法。

          words = ['This', 'is', 'an', 'example', 'of', 'a', 'short', 'sentence.']
          words_without_e = [ word for word in words if 'e' not in word ]
          
          print(words_without_e)
          

          【讨论】: