在变量中用括号将每个元素分开,并找出发生的情况

2024-04-19 21:43:23 发布

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

我有一个文本文件,其中附加了数组'image' 我想做的是从文本文件中提取它,并计算出文本文件中每个单词出现index[2]的次数。例如hablar出现一次等,然后我会用它来绘制一个图

问题是,当我导入文件时,它是一个列表中的一个列表

with open("wrongWords.txt") as file:
    array1 = []
    array2 = [] 
    for element in file:
        array1.append(element)    
    x=array1[0]
    print(x)

打印x给我

(12, 'a', 'hablar', 'to speak')(51, 'a', 'ocurrir', 'to occur/happen')(12, 'a', 'hablar', 'to speak')(2, 'a', 'poder', 'to be able')(11, 'a', 'llamar', 'to call/name')


Tags: 文件to列表index绘制数组element单词
1条回答
网友
1楼 · 发布于 2024-04-19 21:43:23

要将string转换为list,请执行以下操作:

>>> s = "(12, 'a', 'hablar', 'to speak')(51, 'a', 'ocurrir', 'to occur/happen')(12, 'a', 'hablar', 'to speak')(2, 'a', 'poder', 'to be able')(11, 'a', 'llamar', 'to call/name')"
>>> s = s.replace(')(', '),(')
# s = "(12, 'a', 'hablar', 'to speak'),(51, 'a', 'ocurrir', 'to occur/happen'),(12, 'a', 'hablar', 'to speak'),(2, 'a', 'poder', 'to be able'),(11, 'a', 'llamar', 'to call/name')"

>>> my_list = list(eval(s))
# my_list = [(12, 'a', 'hablar', 'to speak'), (51, 'a', 'ocurrir', 'to occur/happen'), (12, 'a', 'hablar', 'to speak'), (2, 'a', 'poder', 'to be able'), (11, 'a', 'llamar', 'to call/name')]

要获取list中每个key(在本例中为索引2)的计数,请执行以下操作:

>>> my_dict = {}
>>> for item in my_list:
...     my_dict[item[2]] = my_dict.get(item[2], 0) + 1
...
>>> my_dict
{'hablar': 2, 'ocurrir': 1, 'poder': 1, 'llamar': 1}

相关问题 更多 >