Split each element by bracket in variable and find occurrence
<p>I have a text file which has arrays appended to them<a href="http://i.stack.imgur.com/2B1zP.png" rel="nofollow"><img src="http://i.stack.imgur.com/2B1zP.png" alt="&#39;image&#39;"></a>
What I want to do is extract it from the text file and work out how many times <code>index[2]</code> occurs for each word in the text file. For instance hablar occurs once etc. I will then use that to plot a graph. </p>

<p>The problem is that when i import the file it comes as a list within a list</p>

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

<p>Printing x gives me </p>

<p><code>(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')</code></p>

<p>To convert your <code>string</code> into <code>list</code>, do:</p>

<pre><code>&gt;&gt;&gt; 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')"
&gt;&gt;&gt; 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')"

&gt;&gt;&gt; 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')]
</code></pre>

<p>To get the count of each <code>key</code> (at index 2 in your case) in <code>list</code>:</p>

<pre><code>&gt;&gt;&gt; my_dict = {}
&gt;&gt;&gt; for item in my_list:
...     my_dict[item[2]] = my_dict.get(item[2], 0) + 1
...
&gt;&gt;&gt; my_dict
{'hablar': 2, 'ocurrir': 1, 'poder': 1, 'llamar': 1}
</code></pre>

python text matplotlib find-occurrences