簡體   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