How can I let my input open a data file and then make it go through the function?

Viewed 31

So I created this function originally that will return '+' for the number of times each letter in a string is returned... and here is my code...

def letterhelper(filename):
    r = list(filename)
    c_r = set(r)
    c_r.remove(' ')
    c_r.remove(',')
    c_r.remove('.')
    f = []
    for x in c_r:
        f.append([-r.count(x), x])
    return f
def charHistogram(filename: str):
    g = letterhelper(str.lower(filename))
    for t in sorted(g):
        print(t[1], (-t[0]) * '+')
print(charHistogram(filename='Lorem ipsum dolor sit amet, consectetur adipiscing '
                             'elit. Praesent ac sem lorem. Integer elementum '
                             'ultrices purus, sit amet malesuada tortor'
                             'pharetra ac. Vestibulum sapien nibh, dapibus'
                             'nec bibendum sit amet, sodales id justo.'))

and here is my output...

e ++++++++++++++++++++++++
t ++++++++++++++++++
s +++++++++++++++++
i ++++++++++++++++
a +++++++++++++++
m ++++++++++++
r ++++++++++++
u ++++++++++++
l +++++++++
n +++++++++
o +++++++++
c +++++++
d +++++++
p +++++++
b +++++
g ++
h ++
j +
v +
None

However, now I'm trying to take in a file and open it and then make it run through charHistogram(filename) so for instance, a file named data.txt contains the following text

data.txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing
        elit. Praesent ac sem lorem. Integer elementum
        ultrices purus, sit amet malesuada tortor
        pharetra ac. Vestibulum sapien nibh, dapibus
        nec bibendum sit amet, sodales id justo.'

I'm trying to change my code so that it will take in files and return the same output as before. From my knowledge of files and opening them, I've tried to do this...

def letterhelper(filename):
    r = list(filename)
    c_r = set(r)
    c_r.remove(' ')
    c_r.remove(',')
    c_r.remove('.')
    f = []
    for x in c_r:
        f.append([-r.count(x), x])
    return f
def charHistogram(filename):
    r = open(filename)
    q = r.read()
    g = letterhelper(str.lower(q))
    for t in sorted(g):
        print(t[1], (-t[0]) * '+')
print(charHistogram('data'))

but then now my output returns this...

e ++++++++++++++++++++++++
t ++++++++++++++++++
s +++++++++++++++++
i ++++++++++++++++
a +++++++++++++++
m ++++++++++++
r ++++++++++++
u ++++++++++++
l +++++++++
n +++++++++
o +++++++++
c +++++++
d +++++++
p +++++++
b +++++

 ++++
g ++
h ++
j +
v +
None

which is different from my original output... what am I doing wrong and what should I change here??

1 Answers

It looks like your data file contains newlines. That's why there is a new char (\n) counted (4 times). You could remove it in letterHelper: c_r.remove('\n')

Related