0

I have a text file which has arrays appended to them'image' What I want to do is extract it from the text file and work out how many times index[2] occurs for each word in the text file. For instance hablar occurs once etc. I will then use that to plot a graph.

The problem is that when i import the file it comes as a list within a list

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

Printing x gives me

(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')

pahan
  • 567
  • 1
  • 8
  • 22
Smith
  • 631
  • 1
  • 5
  • 11

1 Answers1

0

To convert your string into list, do:

>>> 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')]

To get the count of each key (at index 2 in your case) in list:

>>> 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}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126