2016-03-15 90 views
0

我正在写一个程序,它从50,000个单词的文件中读取,它需要获得没有字母'e'的单词的百分比。我可以让程序打印所有没有e的单词,但是我想把它们附加到列表中,以便我可以得到列表中元素的总和。我现在拥有的每一次运行结果都是0。它也产生了正确的总量。对不起,我不是Python中最好的。从python中的文件中附加特定单词到列表

f=open("hardwords.txt") 

def has_no_e(f): 
    words = [] 
    sum_words= len(words) 
    total = sum(1 for s in f) 
    print total 
    print sum_words 
    letter = 'e' 
    for line in f: 
     for l in letter: 
      if l in line: 
       break 
     else: 
      words.append(line) 

has_no_e(f) 
+0

请提供您的输入样本。 –

回答

1

你不需要收集单词,只需要数它们。

未经测试:

total = 0 
without_e = 0 
with open("hardwords.txt") as f: 
    for line in f: 
     total = total + 1 
     if not 'e' in line: 
      without_e = without_e + 1 

percentage = float(without_e)/float(total) 
+0

你认为每一行都是一个单词。 OP没有提到这一点。 – Bharel

+0

@Bharel OP没有提供*任何*输入样本。我们可以承担任何事。 –

0

这个怎么样:

def has_no_e(): 
    with open(path, "r") as f: 
     words = [word.strip() for line in f.readlines() for word in line.strip().split(',')] 
     words_without_e = [word for word in words if 'e' not in word] 
     print len(words), words 
     print len(words_without_e), words_without_e 

has_no_e() 

现在你只需要计算百分比

0

这确实就是这么回事,

def has_no_e(path): 
    total_words = 0 
    words_without_e = 0 
    with open(path, "r") as f: 
     for line in f: 
      words = line.lower().split() 
      total_words += len(words) 
      words_without_e += sum("e" not in w for w in words) 

    return (float(words_without_e)/total_words)*100 
+1

'len()'会出错。生成器表达式没有长度。如果你想避免构建一个你并不需要的临时列表,可以使用'sum(“e”不用于w的单词)“。 –

+0

@Sven谢谢队友,固定。 – Bharel

0

这是一个possibl e方式:

with open('G:\Tmp\demo.txt', 'r') as f: 
    total = 0 
    count = 0 
    for line in f: 
     words = line.split() 
     total = total + len(words) 
     count = count + len([w for w in words if w.find('e') > 0]) 

print 'Total word:{0}, counted:{1}'.format(total, count) 
相关问题