【问题标题】:Why is my code returning an error for this problem?为什么我的代码会针对此问题返回错误?
【发布时间】:2022-01-03 10:35:30
【问题描述】:

所以我编写了这段代码,它接收一个文件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 .....”时提供的所有字符串输入??

【问题讨论】:

    标签: python list function file


    【解决方案1】:

    以下内容将解决该问题,并使您更容易添加更多字符以供将来删除。

    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] * "+")
    

    【讨论】:

    • 关于str.lower(q):我已经十多年没有看到str.lower 被这样使用了。 q.lower() 是要走的路。字符串本身有lower 方法,所以我们应该使用它。
    【解决方案2】:

    简单:

    if ',' in c_r:
        c_r.remove(',')
    

    这应该是一种高效的操作。

    【讨论】:

      猜你喜欢
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2021-06-09
      • 2016-08-03
      • 1970-01-01
      • 2017-12-30
      • 1970-01-01
      相关资源
      最近更新 更多