【问题标题】:TypeError: 'generator' object is not callable. When trying to iterate over string dataTypeError:“生成器”对象不可调用。尝试迭代字符串数据时
【发布时间】:2019-02-27 22:59:41
【问题描述】:

早安,

我的目标是创建一个函数,接收作为字符串的文本data,并将其转换为小写字母。我希望稍后通过传入数据来应用该函数。

但是,当我调用/应用该函数并尝试在其中传递数据时,我不断输出此错误。

TypeError: 'generator' 对象不可调用

我做了一些进一步的研究,我只是好奇映射是否会导致这个问题?

有没有什么办法可以使功能以最有效的方式工作。

下面是我的代码:

def preprocess_text(text):
    """ The function takes a parameter which is a string.
    The function should then return the processed text
    """  
    # Iterating over each case in the data and lower casing the text
    edit_text = ''.join(map(((t.lower().strip()) for t in text), text))

    return edit_text

然后测试功能看是否有效:

# test function by passing in data. 
""" This is when then the error occurs!""" 
text_processed = preprocess_text(data) 

非常感谢帮助我了解问题所在以及正确的解决方法。 提前干杯!

【问题讨论】:

    标签: python string loops nlp iteration


    【解决方案1】:

    错误出现在您的地图功能中,我认为您没有理解它是如何正常工作的。它有 2 个参数:

    • function_to_apply:接收可迭代的每个元素并返回一个值。`
    • list_of_inputs:您的数据列表(示例中的文本)

    你的第一个参数不是一个函数,只是一个列表,所以改变它:

    ''.join(map(lambda t: t.lower().strip(), text))
    

    匿名 lambda 函数的参数 t 对应于您在 for t in text 中的每一段文本。希望这个例子能阐明它是如何工作的!

    【讨论】:

    • 谢谢!有用!只是好奇有没有办法在不涉及地图的情况下做到这一点?如果有请分享。谢谢! @JosepJoestar
    • 也许''.join(x).lower().strip().replace(' ', '') - 没有迭代。
    • ''.join([item.lower().strip() for item in x]) - 使用列表理解。
    • 你也不能使用 join 两个 map,而使用 functools 的 reduce:reduce(lambda acc, x: acc + x.lower().strip(), text, '')
    • @DeepakM 是的,你只能在那里传递一个列表 - x 变量。请指定您的data strucure
    【解决方案2】:

    您对 map 函数的执行似乎有点错误。根据文档,它应该是:

    map(callable, iterable)
    

    但是您传递的不是可调用的,而是生成器表达式:

    (t.lower().strip()) for t in text)
    

    作为列表理解的结果。 Map 将函数(可调用)作为第一个参数。所以,你可以使用:

    def preprocess_text(text):
    edit_text = ''.join(map(lambda t: t.lower().strip(), text))
    return edit_text
    

    【讨论】:

      猜你喜欢
      • 2018-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 2019-05-28
      • 1970-01-01
      • 2020-12-27
      • 2015-08-02
      相关资源
      最近更新 更多