Python:循环.txt文件并计算项目的出现次数

时间:2016-05-02 22:52:08

标签: python

如果我有一个.txt文件,每行都有一个数字,例如:

7
7
6
5
4
3
1

我想循环遍历文件的内容并计算每个整数的数量(例如,数字7列出两次,所以我会有2个),最好的方法是什么?以下是我目前的情况:

fname = input("Enter Filename: ")
infile = open(fname, "r")
data = infile.readline()

mylist = [0,0,0,0,0,0,0,0,0,0,0]

for i in infile:
    mylist[int(i)] = mylist[int(i)]+1

这似乎不起作用。例如,当我打印mylist [2]时,它应该在文件中给出2的计数。在这种情况下,它们都保留为0,因为我之前分配过它们。

3 个答案:

答案 0 :(得分:1)

我相信您的代码确实有效,但有一个例外,请注明以下内容:

fname = input("Enter Filename: ")
infile = open(fname, "r")
data = infile.readline() # you never use this

mylist = [0,0,0,0,0,0,0,0,0,0,0]

for i in infile:
    mylist[int(i)] = mylist[int(i)]+1

在提到评论的地方,你基本上把文件的第一行扔掉。否则,我能够成功运行此代码。是否有其他未显示的代码片段可能导致问题?

答案 1 :(得分:0)

看起来你想要文件中每个数字的计数值,使用字典来分配值。如果每一行都有一个数字,那么这应该有效。

    Dim String1 As String
    Dim String2 As String
    Dim TestString As String
    Dim Location As Integer

    String1 = "Hello"
    String2 = "Goodbye"
    TestString = "Hello and Goodbye"
    Location = InStr(1, TestString, (String1 & "*" & String2), vbTextCompare)
    If Location >= 1 then
        'Do Something
    End If

答案 2 :(得分:-1)

这是一种可能使用集合模块

执行所需操作的方法
from collections import Counter

def print_top(filename):
    """
    receives a file path, opens it, counts how many times each word appeared in the file and prints the top 20 most
    common words in the file and the amount of times they appeared in a "'word' has appeared 'amount' times" format
    """
    input_file = open(filename, "r")
    wordcount = Counter(input_file.read().split())
    top_20_tuple_list = wordcount.most_common(20)  # finds the top 20 most common words in the wordcount dictionary
    for i in range(len(top_20_tuple_list)):  # and puts them in a list made of tuples in a (word, count) format
        print "%s has appeared in the text %d times" % (top_20_tuple_list[i][0], top_20_tuple_list[i][1])
    input_file.close()
相关问题