Python - 从文件中获取数字列表,并以字母表示形式返回 [英] Python - Obtain a list of numbers from a file and return as dict representation

查看:131
本文介绍了Python - 从文件中获取数字列表,并以字母表示形式返回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法从文件中读取内容并将其作为字典返回。每个文件包含由\\\
分隔的数字,目标是计算返回每个数字作为键的数字,键值是文件中的次数。

I'm having trouble reading from a file and returning the contents as a dictionary. Each file contains numbers separated by \n and the goal is to count the numbers returning each number as a key and the value of the key is the number of times it was in the file.

示例:当 filea.txt 包含
1\\\
1\\\
1\\\
2\\\
3\\ \\ n3\\\
3\\\
3\\\
5\\\
函数应该返回
{1:3,2:1,3:4,5 :1}

filea.txt 包含100\\\
100\\\
3\\ \\ n100\\\
9\\\
9\\\
函数应该返回 {100:3,3:1,9:2}
fileb.txt 包含13\\\
13\\\
13\\\
13\\\
13\\\
13\\\
13\\\
13 \\\
函数应该返回 {13:8}

Example: when filea.txt contains "1\n1\n1\n2\n3\n3\n3\n3\n5\n" the function should return {1:3,2:1,3:4,5:1}
when filea.txt contains "100\n100\n3\n100\n9\n9\n" the function should return {100:3, 3:1, 9:2} when fileb.txt contains "13\n13\n13\n13\n13\n13\n13\n13\n" the function should return {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可以包含不同的信息,功能需要解决这个问题。感谢任何人帮助

Currently this is giving me the error no such file or directory and I believe it's because the contents of the file change in different test cases. So filea can contain different information and the function needs to account for this. Thanks to anyone who helps

推荐答案

这样的东西就够了。请记住,没有进行验证。例如,空行,非数字字符。在你的问题中,似乎数字应该被转换为一个整数,但你的代码不是这样我也包括它。

Something like this should suffice. Keep in mind that no validation has been done. Eg, blank lines, non-numeric characters. In your question is seemed like the numbers should be converted to an integer but your code doesn't so I included it anyway.

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')

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

You are reading two files and ignoring the filename given as a parameter.

info = a.read()

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

This will read in the whole file, typically not the best when it comes to large files.

if info == True:

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

info will never be True as it is a string.

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

这通常很好,但是你没有格式化信息仍然是一个字符串,所以您的字典包含 \\\
字符,它不适用于具有超过1个字符的数字,因为它计算每个单独的字符。

This is typically fine, however you haven't formatted info as it is still a string, so your dictionary included the \n characters, it doesn't work for digits with more than 1 character as it counts each individual character.

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

You are most likely getting an IOError. You need your text files in the same directory as your python file if you want to just use the filename, otherwise you have to supply the file path

这篇关于Python - 从文件中获取数字列表,并以字母表示形式返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆