所以我寫了這段代碼,它接受一個文件,filename: str
並以 '+' 的形式返回字符串中每個字母存在的次數..這是我的代碼
def letterhelper(filename):
r = list(filename)
c_r = set(r)
c_r.remove(' ')
c_r.remove(',')
c_r.remove('.')
c_r.remove('\n')
f = []
for x in c_r:
f.append([-r.count(x), x])
return f
def charHistogram(data: str):
r = open(filename)
q = r.read()
g = letterhelper(str.lower(q))
for t in sorted(g):
print(t[1], (-t[0]) * '+')
和數據是一個單獨的文件,它將被函數打開 letterhelper()
數據可能包含的示例輸入是...
“我的兄弟姐妹給我壓力”
所以,問題是,當data
是
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.
函數正確返回
e ++++++++++++++++++++++++
t ++++++++++++++++++
s +++++++++++++++++
i ++++++++++++++++
a +++++++++++++++
m ++++++++++++
r ++++++++++++
u ++++++++++++
l +++++++++
n +++++++++
o +++++++++
c +++++++
d +++++++
p +++++++
b +++++
g ++
h ++
j +
v +
None
但如果data
=Someday Imma be greater than the rest
輸出是
c_r.remove(',')
KeyError: ','
我應該進行哪些更改,以便我的代碼正確返回直方圖,例如data
“Lorem ipsum .....”何時為提供的所有字符串輸入?
以下內容將解決該問題,並使您將來可以更輕鬆地添加更多字符以進行刪除。
def letterhelper(filename):
r = list(filename)
c_r = set(r)
chars_to_remove = (' ', ',', '.', '\n')
for char in chars_to_remove:
if char in c_r:
c_r.remove(char)
f = []
for x in c_r:
f.append([-r.count(x), x])
return f
.
.
.
.
.
.
如果您需要有關代碼的建議。
def letterhelper(filename): # I GUESS you wanted the parameter here to be 'data' and not 'filename'
r = list(filename) # You don't need to convert str to list for using 'count' method
c_r = set(r)
chars_to_remove = (' ', ',', '.', '\n')
for char in chars_to_remove:
if char in c_r:
c_r.remove(char)
f = [] # You can use list comprehentions
for x in c_r:
f.append([-r.count(x), x]) # you don't need to negate the count here, you can reverse the sorted list in the function 'charHistogram'
return f
def charHistogram(data: str): # I GUESS you wanted the parameter here to be 'filename' and not 'data'
r = open(filename) # It is always a good practice to close the file as soon as you are done with it
q = r.read()
g = letterhelper(str.lower(q))
for t in sorted(g): # sorted(g, reverse=True)
print(t[1], (-t[0]) * '+') # t[0] * '+'
以下是我能想到的。
def letterhelper(data: str):
chars_to_remove = (" ", ",", ".", "\n")
# f = []
# for x in set(data):
# if x not in chars_to_remove:
# f.append((data.count(x), x))
# The list comprehention in the next line does exactly the same thing as the for loop above
f = [(data.count(x), x) for x in set(data) if x not in chars_to_remove]
return f
def charHistogram(filename: str):
# r = open(filename)
# q = r.read()
# r.close()
# The with statement in the next line does exactly the same thing as the 3 lines above
with open(filename) as r:
q = r.read()
g = letterhelper(str.lower(q)) # q.lower() will also work
for t in sorted(g, reverse=True): # this will sort the list in descending order
print(t[1], t[0] * "+")
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句