在变量中用括号拆分每个元素并找到出现的地方
Split each element by bracket in variable and find occurrence
我有一个文本文件,其中附加了数组
我想要做的是从文本文件中提取它并计算出文本文件中每个单词出现了多少次 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')
要将您的 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}
我有一个文本文件,其中附加了数组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')
要将您的 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}