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

2024-03-28 14:09:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图计算一个文本文件的列表总数和元素总数。文本文件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>

Tags: pathintxt列表forreaddataast
1条回答
网友
1楼 · 发布于 2024-03-28 14:09:07

这个问题不是空名单!这是字符串末尾的LF。你知道吗

此代码适用于python 3.6:

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

如果此错误在旧版本上仍然存在,并且python升级不是一个选项,请在计算表达式之前删除空列表:

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

相关问题 更多 >