简体   繁体   English

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

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

I am trying to compute the total number of lists and total number of elements of a text file.我正在尝试计算文本文件的列表总数和元素总数。 The text file try1.txt consists of a list of lists structure like this:文本文件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()

The output for the above mentioned input list should be: 3 and 9.上述输入列表的输出应为:3 和 9。

I have tried but I am getting error when there is a empty list.我已经尝试过,但是当列表为空时出现错误。 Is there any way to solve the issue?有没有办法解决这个问题? If not then I want to display the output by removing the empty lists;如果没有,那么我想通过删除空列表来显示输出; in that case the output should be 2 and 9.在这种情况下,输出应该是 2 和 9。

If I remove the empty list, then I am getting the output as 2 and 9. But the inclusion of empty list creating problem.如果我删除空列表,那么我得到的输出为 2 和 9。但是包含创建问题的空列表。 The error I am getting:我得到的错误:

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

This problem was not the empty list!这个问题不是空列表! It's the LF at the end of the string.它是字符串末尾的 LF。

This code work on python 3.6:此代码适用于 python 3.6:

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

If the error persists on a older version and python upgrade is not a option, just remove the empty list before evaluate the expression:如果错误在旧版本上仍然存在并且 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