[英]How to read a CSV file line by line and store it to new CSV file on new row every time?
我是Python的新手。 我正在尝试读取CSV文件,并且从文件中删除停用词后,必须将其存储到新的CSV文件中。 我的代码删除了停用词,但是它将第一行复制到文件的每一行中。 (例如,如果文件中有三行,那么它将在第一行中复制第一行三遍)。
正如我分析过的那样,我认为问题出在循环中,但我没有得到。 我的代码附在下面。
码:
import nltk
import csv
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def stop_Words(fileName,fileName_out):
file_out=open(fileName_out,'w')
with open(fileName,'r') as myfile:
line=myfile.readline()
stop_words=set(stopwords.words("english"))
words=word_tokenize(line)
filtered_sentence=[" "]
for w in myfile:
for n in words:
if n not in stop_words:
filtered_sentence.append(' '+n)
file_out.writelines(filtered_sentence)
print "All Done SW"
stop_Words("A_Nehra_updated.csv","A_Nehra_final.csv")
print "all done :)"
您只读取文件的第一行: line=myfile.readline()
。 您要遍历文件中的每一行。 一种方法是
with open(fileName,'r') as myfile:
for line in myfile:
# the rest of your code here, i.e.:
stop_words=set(stopwords.words("english"))
words=word_tokenize(line)
另外,你有这个循环
for w in myfile:
for n in words:
if n not in stop_words:
filtered_sentence.append(' '+n)
但是您会注意到,最外层循环中定义的w
从未在循环内部使用。 您应该可以删除它,然后写
for n in words:
if n not in stop_words:
filtered_sentence.append(' '+n)
编辑:
import nltk
import csv
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
def stop_Words(fileName,fileName_out):
file_out=open(fileName_out,'w')
with open(fileName,'r') as myfile:
for line in myfile:
stop_words=set(stopwords.words("english"))
words=word_tokenize(line)
filtered_sentence=[""]
for n in words:
if n not in stop_words:
filtered_sentence.append(""+n)
file_out.writelines(filtered_sentence+["\n"])
print "All Done SW"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.