TypeError:“int”对象不可iterable。迭代字符串d中的每个字符串时

2024-04-26 21:50:03 发布

您现在位置:Python中文网/ 问答频道 /正文

你好

我的目标是使用.lower()将文本数据中的每个字符串转换为小写。我尝试将.count()与一个线性迭代结合使用。但是,我得到以下错误:

TypeError: 'int' object is not iterable

这是我的密码:

# Iterating over the strings in the data. The data is called text
text_lowercase = ''.join((string.lower().strip() for string in text.count(0,)))

我想使用一个线性迭代来做这个。 我们将非常感谢您的帮助。干杯!你知道吗


Tags: the数据字符串textin文本目标data
3条回答

这里有几个问题需要指出:

text_lowercase = ''.join((string.lower().strip() for string in text.count(0,)))

命名临时变量string是个坏主意,因为它看起来很像类型名。像s这样的东西更常见、更可读。你知道吗

或者word因为这就是你想要的。这是第二个问题,您的方法似乎将字符串分解为字符,但从注释来看,您似乎希望对单词进行操作?(使用strip也表明了这一点)

您将在''上加入,这将导致字符串的所有部分都被加入,它们之间没有空格。你知道吗

正如其他人指出的,count返回一个整数,但您希望对实际字符串进行操作。您指出您只尝试了count来迭代,而这在Python中是不需要的,就像在许多其他语言中一样。你知道吗

拼凑成文字:

text_lowercase = ' '.join([w.lower() for w in text.split(' ')])

或者如果你在追求人物:

text_lowercase = ''.join([ch.lower() for ch in text])

但是你可以:

text_lowercase = text.lower()

也许你喜欢单词,但想去掉多余的空格?你知道吗

text_lowercase = ' '.join([w.lower() for w in text.split(' ') if w != ''])

或者用速记法:

text_lowercase = ' '.join([w.lower() for w in text.split(' ') if w])

text.count返回一个整数。您尝试对其进行迭代:

for string in text.count(0,)

但是由于它返回一个整数,因此没有in(它不是iterable)。这就是错误消息告诉您的。你知道吗

将来,为了更好地识别错误的来源,请尝试将一行代码分解为多行。这将给你更好的反馈,你的行动是失败的一部分。你知道吗

你得到的例外是因为count()返回一个int,然后你尝试遍历该int。我认为你应该删除count,你可能会很好地去做(取决于text看起来如何)

如果您想要有一个函数,它只降低string实例在text中的大小写,也许您可以使用这样的方法:

def lowercase_instance(text, string):
    return string.lower().join(text.split(string))

现在,如果你有一个文本列表,那么你可以这样做:

lowercase_texts = [lowercase_instance(text, string) for text in texts]

希望这有帮助!你知道吗

相关问题 更多 >