-1
find = open("words.txt")

def noE():    
    for line in find:
        if line.find("e") == -1:
            word = line.strip()
            print word,

noE()

上面的代码在 .txt 文件中搜索所有不包含字母“e”的单词,然后打印出来。如果有条件,我希望能够在此条件下计算总字数。我查看了 python 文档并找到了 Count() 但导入对我不起作用(假设我做错了什么)。任何帮助将非常感激!

4

2 回答 2

3

for只需在循环中添加一个计数器变量。

另外,不要使用line.find('e'). 请改用in关键字:

with open('words.txt', 'r') as handle:
    total = 0

    for line in handle:
        if 'e' not in line:
            total += 1
            word = line.strip()

            print word,
于 2013-01-14T01:00:38.293 回答
0

如果您想将这些词用于其他内容,这将更加pythonic,并且有用:

find = open("find.txt")

noes = [line.strip() for line in find if line.find("e")== -1]

print(noes)
print(len(noes))
于 2013-01-14T01:10:11.570 回答