0

So I have having trouble making a tuples list in ascending order that removes special characters. So far, I am able to strip to each character and gain a count as well as printing in ascending order. However I have been unsuccessful in removing special characters from the strings and they are included in my count. I understand I need to use the .translate method and include string.punctuation, but I haven't been able to place it in the right area. Here is my code.

import string

def Tuplelist():
    fname = input('Please enter file name to process: ')
    try:
        fopen = open(fname)
    except:
        print('file name', fname, "doesn't exist.")
        return
    counts = {}
    for line in fopen:
        words = line.strip('\n')
        word2 = words.lower()
        wordy = word2.split()
        for word in wordy:
            for letter in word:
                counts[letter] = counts.get(letter,0) + 1
    listletter = []
    for key, val in counts.items():
        listletter.append((key, val))
    print( sorted ( [ (v,k) for k,v in counts.items() ] ) )

I am still unable to convert the special characters by inserting string.punctuation as it states "'dict object has no attribute "translate"".

moosegumps
  • 43
  • 4
  • Does this answer your question? [How to remove punctuation marks from a string in Python 3.x using .translate()?](https://stackoverflow.com/questions/34293875/how-to-remove-punctuation-marks-from-a-string-in-python-3-x-using-translate) – vasia Nov 29 '20 at 22:51
  • 1
    You have to apply this method to a string, not a dict. You can update the line `words = line.strip('\n')` to `words = line.strip('\n').translate(str.maketrans('', '', string.punctuation))`. – Cainã Max Couto-Silva Nov 30 '20 at 02:20
  • This was a helpful explanation, much appreciated! – moosegumps Nov 30 '20 at 02:23

0 Answers0