繁体   English   中英

如何在列表中没有字母'e'的单词上打印?

[英]How do I print the words on a list that do not have the letter 'e'?

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

第2至6行是读取单词并返回带有字母e的True为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))

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

def has_no_e(word):
  if 'e' in word:
    return True
  else:
    return False

此功能与它的名称相反。 如果单词的确包含'e',则返回True

检查这是否在功能中起作用。

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

像这样:(对于前10个字):

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

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

for word in fin:

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

另外,如果word不包含ehas_no_e()应该返回True ,则其实现应包含以下行:

    if 'e' in word:

替换为

    if 'e' not in word:

我希望这段代码是正确的

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”的单词,而不是没有单词的单词。

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM