来自Think Python的has_no_e()练习

时间:2013-06-04 12:30:21

标签: python filter

这是来自Think Python。试图浏览文件的每一行(每行一个单词),只打印出不包含字母e的每个单词。 我花了4个小时尝试不同的方式通过我的函数过滤文件,但我放弃了。似乎它只过滤掉它在一个单词中找到的第一个:如果一个单词有两个e而不是它打印它无论如何。

def has_no_e():
    file_name = raw_input('Enter the full path and file name: ') 
    fin = open(file_name)   
    line = fin.readline()

    for line in fin:
        word = line.strip()
        print word
        for letter in word:
            if letter == 'e':
                continue
            print word




    has_no_e()

我的代码缩进顺便说一句,我认为当我按住ctrl + v

时它会变得混乱

如果有办法让我的代码更短,请告诉我:]

2 个答案:

答案 0 :(得分:4)

with open(filename) as f:
    for line in f:
        if not 'e' in line: print line.strip()

一些意见:

  • 在使用文件时使用,虽然它是python中的一个较新的构造,它可以帮助您管理文件(即在不再需要时再次关闭它)
  • word = line.strip()使您的代码无法读取。使用line = line.strip()(您只会使用lineword,而不是两者,我认为

那么为什么你的代码不起作用?

for letter in word:
    if letter == 'e':
        continue
    print word

在这里,您将单词分成字母,然后检查字母是否等于e。如果不是这种情况,则打印该单词,否则跳转到下一个字母。因此,您可以多次打印该字,因为字母与“e”不同。

解决这个问题的方法是定义一个布尔值,它告诉你单词中是否有e:

hasE = False
for letter in word:
    if letter == 'e':
        hasE = True
        break
if not hasE: print word

请注意,Python也有一种奇特的方法来解决这样的问题:

for letter in word:
    if letter == 'e': break
else:
    print word

答案 1 :(得分:0)

看起来pfnuesel认为代码在他写道时没有工作的主要原因是:

  

"在这里你将单词分成字母,然后你检查是否   字母等于e。如果情况并非如此,则打印单词,   否则你跳到下一个字母。所以你打印这个词就多了   因为有些字母不同于'。"

这就是我在Think Python中解决练习9.2的方式:

def has_no_e(word):
    return "e" not in word

fin = open('words.txt')

for line in fin:
    word = line.strip()
    if has_no_e(word):
        print word
相关问题