【问题标题】:Python - Obtain a list of numbers from a file and return as dict representationPython - 从文件中获取数字列表并以 dict 表示形式返回
【发布时间】:2017-03-20 07:42:05
【问题描述】:

我在读取文件并将内容作为字典返回时遇到问题。每个文件都包含由 \n 分隔的数字,目标是计算返回每个数字作为键的数字,键的值是它在文件中的次数。

示例:当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 可以包含不同的信息,函数需要考虑到这一点。感谢所有帮助的人

【问题讨论】:

    标签: list file python-3.x dictionary numbers


    【解决方案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 文件放在同一目录中,否则您必须提供文件路径

    【讨论】:

    • 感谢您解释为什么我的代码除了您的解决方案之外无法正常工作,这真的很有帮助
    【解决方案2】:

    从您的声明中,我假设您收到了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”分别计算 3 次,而不是 100 计算 3 次。相反,您可以列出如下值:

    >>> 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}
    

    您的输入和最后的 if then 语句仍有一些错误,但我会让您先对它们进行测试。 GL!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 2018-10-09
      • 2015-06-18
      • 2022-01-19
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      相关资源
      最近更新 更多