使用python编辑csv列 [英] Edit csv column using python

查看:52
本文介绍了使用python编辑csv列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使csv文件中的第2列全部为小写字母,并删除所有标点符号并保存该文件.我该怎么办?

I would like to make column 2 in the csv file to be all lowercase and removing all the punctuation and save the file. How can i do that?

import re
import csv

with open('Cold.csv', 'rb') as f_input1:
    with open('outing.csv', 'wb') as f_output:

      reader = csv.reader(f_input1)
      writer = csv.writer(f_output)

for row in reader:
      row[1] = re.sub('[^a-z0-9]+', ' ', str(row[1].lower()))
      writer.writerow(row)
f_input1.close()

我如何添加:

re.sub('[^A-Za-z0-9]+', ' ', str(row))
filewriter.writerow([new_row.lower()]) 

还是此代码中的低位?

推荐答案

您可以添加代码来修改单元格,如下所示:

You could add your code to modify your cell as follows:

import re
import csv

with open('in.csv', 'rb') as f_input, open('out.csv', 'wb') as f_output:
    csv_output = csv.writer(f_output)

    for row in csv.reader(f_input):
        row[1] = re.sub('[^A-Za-z0-9]+', '', row[1].lower())
        csv_output.writerow(row)

.lower()用于首先将字符串转换为小写.结合使用可以确保两个文件最后都自动关闭.

.lower() is used to first convert the string to lowercase. Using with ensures that your files are both automatically closed at the end.

请注意,您的正则表达式子程序应将所有无效字符替换为空字符串,例如'',您当前已将其设置为单个空格.

Note, your regular expression sub should replace any invalid characters with an empty string, e.g. '', you currently have it set to be a single space.

这篇关于使用python编辑csv列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆