Smith Smith -4 years ago 204
Python Question

Split each element by bracket in variable and find occurrence

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

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:

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

Answer Source

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}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download