python输出文本 去掉引号_在文本文件中读取时,Python可以从字符串中删除双引号吗?...

1586010002-jmsa.png

I have some text file like this, with several 5000 lines:

5.6 4.5 6.8 "6.5" (new line)

5.4 8.3 1.2 "9.3" (new line)

so the last term is a number between double quotes.

What I want to do is, using Python (if possible), to assign the four columns to double variables. But the main problem is the last term, I found no way of removing the double quotes to the number, is it possible in linux?

This is what I tried:

#!/usr/bin/python

import os,sys,re,string,array

name=sys.argv[1]

infile = open(name,"r")

cont = 0

while 1:

line = infile.readline()

if not line: break

l = re.split("\s+",string.strip(line)).replace('\"','')

cont = cont +1

a = l[0]

b = l[1]

c = l[2]

d = l[3]

解决方案

The csv module (standard library) does it automatically, although the docs isn't very specific about skipinitialspace

>>> import csv

>>> with open(name, 'rb') as f:

... for row in csv.reader(f, delimiter=' ', skipinitialspace=True):

... print '|'.join(row)

5.6|4.5|6.8|6.5

5.4|8.3|1.2|9.3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值