簡體   English   中英

Python輸入和輸出文件

[英]Python Input and output files

遇到問題。 (對即將舉行的考試進行審查)。 第一個問題要求我將每行文本中的單詞數量打印到輸出文件中。 這是一個容易的任務。 (將提供我使用的代碼)。 另一個類似的問題是,在每一行文本中打印唯一單詞的數量(數量)。 我能得到的最遠的結果是將單詞追加到列表中,並打印列表的長度...但是最終添加了每次迭代。 因此它將打印7,14,21。 而不是7,7,7(僅作為示例幫助exapain),我將如何修復此代碼以使其正常運行? 我已經嘗試了最后30分鍾。 任何幫助,將不勝感激!

每行字數的代碼:

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(wordlst)
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

每行中唯一字數的代碼(失敗):

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    unique = []
    for line in inf:
        wordlst = line.split()
        for word in wordlst:
            if word not in unique:
                unique.append(word)
        outf.write(str(len(unique)))

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

如果第一個可行,請嘗試set

def uniqueWords(inFile,outFile):
    inf = open(inFile,'r')
    outf = open(outFile,'w')
    for line in inf:
        wordlst = line.split()
        count = len(set(wordlst))
        outf.write(str(count)+'\n')

    inf.close()
    outf.close()
uniqueWords('turn.txt','turnout.txt')

暫無
暫無

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

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