簡體   English   中英

在Python中遍歷文件對象不起作用,但是readlines()可以,但是效率低下

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

在以下代碼中,如果我使用:

for line in fin:

它僅針對“ a”執行

但是,如果我使用:

wordlist = fin.readlines()
for line in wordlist:

然后執行一遍z。

但是readlines()一次讀取整個文件,我不希望這樣。

如何避免這種情況?

def avoids():
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    num_words = {}

    fin = open('words.txt')

    for char in alphabet:
      num_words[char] = 0
      for line in fin:
        not_found = True
        word = line.strip()
        if word.lower().find(char.lower()) != -1:
          num_words[char] += 1
    fin.close()
    return num_words

for line in fin的語法只能使用一次。 完成此操作后,您已經用盡了文件,除非您通過fin.seek(0) “重置文件指針”,否則無法再次讀取文件。 相反, fin.readlines()將為您提供一個列表,您可以反復遍歷。


我認為使用Counter (python2.7 +)進行簡單的重構可以為您省去麻煩:

from collections import Counter
with open('file') as fin:
    result = Counter()
    for line in fin:
        result += Counter(set(line.strip().lower()))

它將計算文件中包含特定字符的單詞數(每行1個單詞)(我相信這是您的原始代碼...如果我錯了,請更正我)

您也可以使用defaultdict (python2.5 +)輕松完成此操作:

from collections import defaultdict
with open('file') as fin:
    result = defaultdict(int)
    for line in fin:
        chars = set(line.strip().lower())
        for c in chars:
            result[c] += 1

最后,把它踢得很老套-我什至不知道什么時候引入了setdefault ...:

fin = open('file')
result = dict()
for line in fin:
    chars = set(line.strip().lower())
    for c in chars:
        result[c] = result.setdefault(c,0) + 1

fin.close()

您有三種選擇:

  1. 無論如何都讀取整個文件。
  2. 嘗試再次遍歷文件之前,請先回到文件的開頭。
  3. 重新設計代碼,以使它不需要多次遍歷文件。

嘗試:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM