美好的一天,
我的目标是创建一个函数接受文本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)
我真的很感激帮助知道问题是什么,并知道正确的方法来做到这一点。提前干杯!
你执行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
错误在你的地图功能中,我想你不明白它是如何正常工作的。它有两个参数:
function_to_apply
:接收iterable的每个元素并返回一个值list_of_inputs
:您的数据列表(示例中的文字)你的第一个参数不是一个函数,只是一个列表,所以改变它:
''.join(map(lambda t: t.lower().strip(), text))
匿名lambda函数的参数t对应于你在qazxsw poi中的每一段文本。希望这个例子澄清它是如何工作的!