python open文件 第一行特殊字符_使用python从CSV文件中删除特殊字符

There seems to something on this topic already (How to replace all those Special Characters with white spaces in python?), but I can't figure this simple task out for the life of me.

I have a .CSV file with 75 columns and almost 4000 rows. I need to replace all the 'special characters' ($ # & * ect) with '_' and write to a new file. Here's what I have so far:

import csv

input = open('C:/Temp/Data.csv', 'rb')

lines = csv.reader(input)

output = open('C:/Temp/Data_out1.csv', 'wb')

writer = csv.writer(output)

conversion = '-"/.$'

text = input.read()

newtext = '_'

for c in text:

newtext += '_' if c in conversion else c

writer.writerow(c)

input.close()

output.close()

All this succeeds in doing is to write everything to the output file as a single column, producing over 65K rows. Additionally, the special characters are still present!

Sorry for the redundant question.

Thank you in advance!

解决方案

I might do something like

import csv

with open("special.csv", "rb") as infile, open("repaired.csv", "wb") as outfile:

reader = csv.reader(infile)

writer = csv.writer(outfile)

conversion = set('_"/.$')

for row in reader:

newrow = [''.join('_' if c in conversion else c for c in entry) for entry in row]

writer.writerow(newrow)

which turns

$ cat special.csv

th$s,2.3/,will-be

fixed.,even.though,maybe

some,"shoul""dn't",be

(note that I have a quoted value) into

$ cat repaired.csv

th_s,2_3_,will-be

fixed_,even_though,maybe

some,shoul_dn't,be

Right now, your code is reading in the entire text into one big line:

text = input.read()

Starting from a _ character:

newtext = '_'

Looping over every single character in text:

for c in text:

Add the corrected character to newtext (very slowly):

newtext += '_' if c in conversion else c

And then write the original character (?), as a column, to a new csv:

writer.writerow(c)

.. which is unlikely to be what you want. :^)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值