iterating over file object in Python does not work, but readlines() does but is inefficient

前端 未结 3 2001
执笔经年
执笔经年 2020-12-04 02:48

In the following code, if I use:

for line in fin:

It only executes for \'a\'

But if I use:

wordlist = fin.readline         


        
3条回答
  •  误落风尘
    2020-12-04 03:15

    Try:

    from collections import defaultdict
    from itertools import product
    
    def avoids():
        alphabet = 'abcdefghijklmnopqrstuvwxyz'
    
        num_words = defaultdict(int)
    
        with open('words.txt') as fin:
            words = [x.strip() for x in fin.readlines() if x.strip()]
    
        for ch, word in product(alphabet, words):
            if ch not in word:
                 continue
            num_words[ch] += 1
    
        return num_words
    

提交回复
热议问题