我正在尝试在csv中编写函数的结果。不幸的是,没有熊猫。
csv文件输入:
Hello all well?
today is cold!
I have not had lunch yet
He does not have many brothers or sisters.
We are sick
脚本:
import re
import csv
import string
with open('teste_csv.csv', 'r') as f:
file = csv.reader(f)
for line in file:
message = ''.join(line)
def toto(message):
message = message.lower()
p = re.compile('|'.join(map(re.escape, string.punctuation)))
no_punct = p.sub(' ', message)
writer = csv.writer(open('result.csv', 'w'))
for row in no_punct:
writer.writerow(row)
return writer
print(toto(message))
在我的终端上,我有,在result.csv中,我只有一行写为'w'。我希望每一行都在我的result.csv中
最佳答案
由于每次调用toto
它都会打开result.csv
进行写入,因此会一直擦除文件,因此只剩下一次写入操作。您需要打开文件一次,并创建一次写入器。您也只需要为此定义一次功能:
import re
import csv
import string
def toto(message,writer):
message = message.lower()
p = re.compile('|'.join(map(re.escape, string.punctuation)))
no_punct = p.sub(' ', message)
for row in no_punct:
writer.writerow(row)
with open('teste_csv.csv', 'r') as f:
writer = csv.writer(open('result.csv','w'))
file = csv.reader(f)
for line in file:
message = ''.join(line)
toto(message,writer)
关于python - 在csv中写入函数的结果,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51537931/