2016-11-07 45 views
0

我无法从文件中读取内容并将其作为字典返回。每个文件都包含以\ n分隔的数字,目标是计算将每个数字作为关键字返回的数字,关键字的值是文件中的次数。Python - 从文件中获取数字列表并返回字典表示形式

例如:当filea.txt包含 "1\n1\n1\n2\n3\n3\n3\n3\n5\n"函数应该返回 {1:3,2:1,3:4,5:1}
filea.txt包含"100\n100\n3\n100\n9\n9\n"函数应该返回{100:3, 3:1, 9:2}fileb.txt包含"13\n13\n13\n13\n13\n13\n13\n13\n"函数应该返回{13:8}

这里是我当前的尝试:

def file_counts(filename): 
    a = open('filea.txt') 
    b = open('fileb.txt') 
    info = a.read() 
    info2 = b.read() 
    a.close() 
    b.close() 
    if info == True: 
     return (dict(collections.Counter(info))) 
    elif info2 == True: 
     return (dict(collections.Counter(info2))) 
    else: 
     return None 

目前这给我的错误没有这样的文件或目录,我相信这是因为文件的内容在不同的测试用例中更改。所以filea可以包含不同的信息,并且该功能需要对此进行解释。由于任何人谁帮助

回答

1

像这样的东西应该就足够了。请记住,没有进行验证。例如,空行,非数字字符。在你的问题看起来好像数字应该被转换为一个整数,但你的代码没有,所以我反正包括它。

from collections import Counter 

def file_counts(filename): 
    # Open file for reading 
    with open(filename, 'r') as file: 
     data = [] 
     # Go through each line of the file 
     for line in file: 
      value = int(line) 
      data.append(value) 

     return dict(Counter(data)) 

if __name__ == '__main__': 
    filename = 'testfile.txt' 
    print(file_counts(filename)) 

您曾经遇到过的问题。

def file_counts(filename): 
    a = open('filea.txt') 
    b = open('fileb.txt') 

您正在阅读两个文件并忽略作为参数给出的文件名。

info = a.read() 

这将在整个文件中读取,对于大型文件通常不是最好的。

if info == True: 

info将永远True,因为它是一个字符串。

return (dict(collections.Counter(info))) 

这是因为它仍然是一个字符串通常正常,但是你没有格式化的信息,所以你的字典包括\n字符,它不超过1个字符位数工作,因为它每次计数个性。

你很可能会得到一个IOError。如果您只想使用文件名,则需要将文本文件放在与python文件相同的目录中,否则您必须提供文件路径

+0

感谢您解释为什么我的代码除了您的代码不工作这个解决方案真的很有用 – n00bprogrammer22

0

从你的说法,我认为你收到了IOError如:

IOError: [Errno 2] No such file or directory: 'filea.txt' 

如果您收到此错误,这是因为open无法找到匹配当前工作目录中的文件您要求它提取的文件名。您需要将路径添加到文件名的开头,例如/home/username/project/filea.txt以确保python正在正确的目录中搜索。

一旦你能够打开你的文件,并通过IOError,你的代码有几个扭结。

首先,让我们来看看dict(collections.Counter(info))

>>> info = "100\n100\n3\n100\n9\n9\n" 
>>> dict(collections.Counter(info)) 
{'1': 3, '0': 6, '3': 1, '\n': 6, '9': 2} 

正如我们所看到的,是collections.Counter()解析字符串中的每个字符和计数每一个的发生。因此,“1”,“0”和“3”分别计数三次而不是三次计数100次。相反,你可以做如下的值的列表:

>>> info = info.strip()  # removes the last \n on the right 
>>> nums = info.split('\n') # breaks up the string into a list of elements 
>>> print(nums) 
['100', '100', '3', '100', '9', '9'] 
>>> print(dict(collections.Counter(nums))) 
{'9': 2, '100': 3, '3': 1} 

你还有关于你输入一些错误,并在结束时,如果再声明,但我会让你先刺他们。 GL!