2016-03-15 89 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) 
相關問題