简体   繁体   English

Python中带有附加的简单循环

[英]simple loop with append in Python

I want to get a loop, so instead of writing me code such: 我想得到一个循环,所以不要像这样写代码:

tfidf = vectorizer.fit_transform([ data[0]['body'] , data[1]['body'] , data[2]['body'] , data[3]['body'] ....  ])

I get it in a loop. 我得到一个循环。 So far I have tried: 到目前为止,我已经尝试过:

for i in range(len(data) - 1):
    tfidf = vectorizer.fit_transform([ append(data[i]['body']) , data[i+1]['body']) ])

Any idea on how to make it work? 关于如何使其工作的任何想法? I get the following error: 我收到以下错误:

name 'append' is not defined 未定义名称“ append”

You need to call append() on a list. 您需要在列表上调用append()。 eg MyList.append(element) 例如MyList.append(element)

I guess you want to extract the 'body' content from the json data and have a list of text elements to then pass it to the feature extractor (make sure you have preprocessed the text before). 我想您想从json数据中提取“正文”内容,并有一系列文本元素,然后将其传递给特征提取器(请确保您已经对文本进行了预处理)。

Try this: 尝试这个:

    tfidf = vectorizer.fit_transform([d['body'] for d in data])

Or, if it is more clear to you, you can create the list first and then pass it to the function: 或者,如果您更清楚,可以先创建列表,然后将其传递给函数:

bodies = [d['body'] for d in data]
tfidf = vectorizer.fit_transform(bodies)

Hope it helps :) 希望能帮助到你 :)

Happy coding !!! 编码愉快!

PD: I haven't tested the code, but I think the idea is clear. PD:我还没有测试代码,但是我认为这个想法很明确。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM