在文本文件中读取时,Python可以从字符串中删除双引号吗? [英] Can Python remove double quotes from a string, when reading in text file?

查看:2763
本文介绍了在文本文件中读取时,Python可以从字符串中删除双引号吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些这样的文本文件,有几行5000行:

  5.6 4.5 6.86.5 
5.4 8.3 1.29.3(新行)



我想要做的是,使用Python(如果可能),将四列分配给双变量。但是主要的问题是最后一个术语,我发现没有办法删除双引号的数字,是否可能在linux?



这是我试过: / p>

 #!/ usr / bin / python 

import os,sys,re,string,array

name = sys.argv [1]
infile = open(name,r)

cont = 0
while 1:
line = infile.readline()
如果不是行:break
l = re.split(\s +,string.strip(line))。replace('\'','' )
cont = cont +1
a = l [0]
b = l [1]
c = l [2]
d = l [3]
尽管文档对 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¥b $ b


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

这篇关于在文本文件中读取时,Python可以从字符串中删除双引号吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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