繁体   English   中英

从具有列表结构列表和空列表的文本文件中查找列表和元素的总数

[英]Finding total number of lists and elements from a text file with list of lists structure and empty lists

我正在尝试计算文本文件的列表总数和元素总数。 文本文件try1.txt包含一个列表结构列表,如下所示:

[[], ['i', 'am', 'a', 'good', 'boy'], ['i', 'am', 'an', 'engineer']] 
import ast
global inputList
inputList = []
path = "C:/Users/hp/Desktop/folder/"
def read_data():
    for file in ['try1.txt']:
        with open(path + file, 'r', encoding = 'utf-8') as infile:
           inputList.extend(ast.literal_eval(*infile.readlines()))
    print(len(inputList))
    print(sum(len(x) for x in inputList))
read_data()

上述输入列表的输出应为:3 和 9。

我已经尝试过,但是当列表为空时出现错误。 有没有办法解决这个问题? 如果没有,那么我想通过删除空列表来显示输出; 在这种情况下,输出应该是 2 和 9。

如果我删除空列表,那么我得到的输出为 2 和 9。但是包含创建问题的空列表。 我得到的错误:

ValueError: malformed node or string: <_ast.Subscript object at 0x0000020E99CC0088>

这个问题不是空列表! 它是字符串末尾的 LF。

此代码适用于 python 3.6:

import ast
v = ast.literal_eval("[[],['i', 'am', 'a', 'good', 'boy'],['i', 'am', 'an', 'engineer']]")`

如果错误在旧版本上仍然存在并且 python upgrade 不是一个选项,只需在评估表达式之前删除空列表:

exp = infile.read()
empty_count = exp.count('[]')
exp = exp.replace('[],','')
inputList.extend(ast.literal_eval(*exp))
print('List Count:%d' % len(inputList)+empty_count)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM