2013-11-21 49 views
0

我試圖讓alist中的值成爲文件中0-9的出現次數。我不知道我在哪裏搞砸了,因爲在運行代碼之後,alist仍然全是0。協助計算文件中的數字

def main(): 
    intro() 
    inFile = getFile() 
    file, outfile = convertName(inFile) 
    alist, count = countLines(file, outfile) 
    printResults(alist, count, outfile) 

def intro(): 
    print() 
    print("Program to count letters in each line") 
    print("in a file.") 
    print("You will enter the name of a file.") 
    print("The program will create an output file.") 
    print("Written by .") 
    print() 
def getFile(): 
    inFile = input("Enter name of input file: ") 
    return inFile 
def convertName(inFile): 
    file = open(inFile, "r") 
    outfile = (inFile.replace(".txt", ".out")) 
    return file, outfile 
def countLines(file, outfile): 
    outfile = open(outfile, "w") 
    alist = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] 
    count = 0 
    for line in file: 
     count = count + 1 
     spl = line.split()  
     for i in range(0,10): 
      for ch in spl: 
       if ch == i: 
        alist[i] = alist[i+1] 
    return alist, count 
def printResults(alist, count, outfile): 
    print("The name of output file is", outfile) 
    print() 
    print("Number of lines:   ", count) 
    t = 0 
    print(alist) 
main() 
+0

'ALIST [I] = ALIST第[i + 1]'應'ALIST [I] = ALIST [I] + 1' –

+0

'ALIST = [v爲K,v在排序(列表(collections.Counter(filter(lambda c:c.isdigit(),itertools.chain.from_iterable(file)))。items()),key = lambda(a,b):int(a)) ]' – inspectorG4dget

回答

1
for i in range(0,10): 
     for ch in spl: 
      if ch.isdigit() and int(ch) == i: 
       alist[i] += 1 
+0

非常感謝你好先生 – user3015970

+0

@ user3015970,請考慮upvote gnibblers的答案,如果它幫助你。 –

1

在:

alist[i] = alist[i+1] 

要指定的元素0至alist[i]。您可能需要做一些事情,如:

+0

我試過了,它仍然沒有改變alist – user3015970

+0

把'print'放在'if ch == i:'裏面,並確保你的程序正在進入它。否則,邏輯程序是錯誤的。 – Christian

0

如果你只是想那些數(不計的數字),使用collections.Counter

from collections import Counter 
def count_digits(file_name): 
    with open(fn): 
     c = Counter([int(character) for character in open(fn).read() if character.isdigit()]) 
    return [c.get(i,0) for i in range(10)] 

,如果你也想的行數,延長方法有點:

from collections import Counter 
def count_digits(file_name): 
    with open(fn) as fh: 
     c = Counter([int(character) for character in fh.read() if character.isdigit()]) 
     digit_counts = [c.get(i,0) for i in range(10)] 
     fh.seek(0) 
     lines_count = sum(1 for line in fh) 
    return digit_counts, line_counts