我正在尝试在csv中编写函数的结果。不幸的是,没有熊猫。csv文件输入:Hello all well?today is cold!I have not had lunch yetHe does not have many brothers or sisters.We are sick脚本:import reimport csvimport stringwith 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))在终端上,我有<_csv.writer对象,位于0x7fee60e57c50>,在result.csv中,我只有一行写为'w'。我希望每一行都在我的result.csv中
2 回答
胡子哥哥
TA贡献1825条经验 获得超6个赞
您需要将编写器放在第一个循环之外。每次循环抛出时,它都会打开并重写文件
您正在定义另一个问题,并在循环内调用toto,以便使用最后一个消息值来调用它。
import re
import csv
import string
with open('test.csv', 'r') as f:
file = csv.reader(f)
writer = csv.writer(open('result.csv', 'w'))
def toto(message):
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)
return writer
for line in file:
print line
message=''.join(line)
print(toto(message))
添加回答
举报
0/150
提交
取消