1

I am trying to get a graph to list A-Z down the Y axis, with A at the top, Z at the bottom (near (0,0)).

It's a cobbled mess right now, since I'm learning how to do this, but here's the relevant code:

from collections import Counter
import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt
from collections import OrderedDict
from operator import itemgetter

myFile = "D:/User/Documents/Data/English Words/words_alpha.txt"

ie_prefix = {}
ie_prefix.setdefault("letter", [])
ie_prefix.setdefault("word",[])
ie_prefix.setdefault("beforec",[])
ie_prefix_sorted = {}

def get_words(file_import):
    global total_words, ie_after_c, ie_after_not_c
  #if I don't do this and just keep the below, I get an error: 'total_words' is not defined when running the print(..., total_words, "total words and", ...) line.
    total_words = 0
    ie_after_not_c = 0
    ie_after_c = 0
    results = []
    with open(file_import) as inputfile:
        for line in inputfile:
            total_words = total_words + 1
            if line.find("ie") != -1:
                pos = line.find("ie")
                ie_prefix["letter"].append(line[pos-1:pos])
                ie_prefix["word"].append(line.strip('\n'))
                if line[pos-1:pos] == "c":
                    ie_prefix["beforec"].append(line.strip('\n'))
                    ie_after_c += 1
                elif line[pos-1:pos] != "c":
                    ie_after_not_c += 1

    ie_prefix_sorted = OrderedDict(sorted(ie_prefix.items()))
    return ie_prefix, total_words, ie_after_not_c, ie_after_c, ie_prefix_sorted


def create_graph(total_words, y_axis, x_axis):
    y_pos = np.arange(len(y_axis))
    fig, ax = plt.subplots()
    plt.barh(y_pos, x_axis, align='center', alpha=0.5)
    plt.yticks(y_pos, y_axis)
    plt.ylabel('Usage')
    plt.title('I before E rule')
    plt.legend()
    plt.show()

get_words(myFile)

# https://stackoverflow.com/questions/20316299/formatting-output-of-counter
ie_count = Counter(ie_prefix["letter"])

ie_count_sorted = sorted(ie_count)  #sorted(ie_count.items()) ## THis will just sort the KEYS I believe
ie_letters = list(ie_count_sorted)

###    
## How to use the SORTED IE Count in the graph, so it goes from A-Z where A is at the TOP, and Z is at the BOTTOM of Y-Axis (Z closest to (0,0))?  
create_graph(total, ie_count, ie_count.values())

FYI here's print(ie_count):

Counter({'r': 2417, 't': 1771, 'l': 1304, 'f': 1034, 'd': 778, 'h': 765, 'p': 753, 'c': 729, 'n': 647, 'm': 536, 'g': 492, 's': 470, 'k': 443, 'v': 273, 'b': 260, 'z': 154, 'u': 134, 'w': 93, 'o': 75, 'x': 73, 'y': 49, 'e': 29, 'a': 26, '': 3, 'j': 2, 'i': 1})

I can't figure out how to rearrange ie_count to be in alphabetical order, keeping the values (2417, 171, etc.) with the keys (letters).

BruceWayne
  • 22,923
  • 15
  • 65
  • 110
  • I'm learning Python, so may have missed something very obvious (such as what the name/type of what I'm trying to do is). I'd appreciate any notes on such, or reasons for downvotes. – BruceWayne Jul 16 '17 at 21:54
  • I haven't downvoted but instead of the `get_words` function (a bit unnecessary because we don't have access to your file so you could simply remove it from the question) you could just insert your `ie_count` instead **and** the function `create_graph` would be interesting – MSeifert Jul 16 '17 at 22:04
  • 1
    @MSeifert - Ah, sorry! Didn't realize I left that out. I'll edit. FYI the words list is [this file](https://github.com/dwyl/english-words/blob/master/words_alpha.txt) from GitHub. – BruceWayne Jul 16 '17 at 22:09

1 Answers1

2

You can sort the .items and unpack the keys and values with zip:

from collections import Counter
from operator import itemgetter

ie_count = Counter({'r': 2417, 't': 1771, 'l': 1304, 'f': 1034, 'd': 778, 'h': 765, 'p': 753, 'c': 729, 'n': 647, 'm': 536, 'g': 492, 's': 470, 'k': 443, 'v': 273, 'b': 260, 'z': 154, 'u': 134, 'w': 93, 'o': 75, 'x': 73, 'y': 49, 'e': 29, 'a': 26, '': 3, 'j': 2, 'i': 1})

cnts_sorted = sorted(ie_count.items(), key=itemgetter(0))
print(cnts_sorted)
# [('', 3), ('a', 26), ('b', 260), ('c', 729), ('d', 778), ('e', 29), 
#  ('f', 1034), ('g', 492), ('h', 765), ('i', 1), ('j', 2), ('k', 443), 
#  ('l', 1304), ('m', 536), ('n', 647), ('o', 75), ('p', 753), ('r', 2417), 
#  ('s', 470), ('t', 1771), ('u', 134), ('v', 273), ('w', 93), ('x', 73), 
#  ('y', 49), ('z', 154)]


letters, vals = zip(*cnts_sorted)
print(letters)
# ('', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
#  'o', 'p', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z')
print(vals)
# (3, 26, 260, 729, 778, 29, 1034, 492, 765, 1, 2, 443, 1304, 536, 647, 75,
# 753, 2417, 470, 1771, 134, 273, 93, 73, 49, 154)
MSeifert
  • 145,886
  • 38
  • 333
  • 352
  • Oh man, that's great! I've seen `zip()` before, but will look more in to it. The final piece is how to rearrange backwards. I tried `reversed(letters)`/`reversed(vals)`, but get "TypeError: object of type 'reversed' has no len()`. – BruceWayne Jul 16 '17 at 22:06
  • 1
    what do you mean by "rearrange backwards"? Do you mean sorted in reverse order? That would be as simple as passing `reverse=True` to `sorted`: `sorted(ie_count.items(), key=itemgetter(0), reverse=True)`. Or just use "slicing" to reverse the tuples: `reversed_letters = letters[::-1]` and `reversed_vals = vals[::-1]` – MSeifert Jul 16 '17 at 22:09
  • Ah, that'll do it! Thanks so much! :D (I went with adding `reverse = True` to `sorted()`. – BruceWayne Jul 16 '17 at 22:11