在文本文件中读取时,Python可以从字符串中删除双引号吗?

Ope*_*way 23 python csv quotes file-io strip

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

5.6  4.5  6.8  "6.5" (new line)
5.4  8.3  1.2  "9.3" (new line)
Run Code Online (Sandbox Code Playgroud)

所以最后一个术语是双引号之间的数字.

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

这是我试过的:

#!/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]
Run Code Online (Sandbox Code Playgroud)

Ned*_*der 31

for line in open(name, "r"):
    line = line.replace('"', '').strip()
    a, b, c, d = map(float, line.split())
Run Code Online (Sandbox Code Playgroud)

这是一种简单的方法,如果(例如)线路上没有四个值,则会引发异常,等等.

  • `shlex`非常专业.它恰好可以完成这项任务,但OP可能更重要的是首先学习一些更基本和更灵活的工具. (7认同)

aby*_*byx 14

您可以在标准库中使用一个名为的模块shlex:

>>> import shlex
>>> print shlex.split('5.6  4.5  6.8  "6.5"')
['5.6', '4.5', '6.8', '6.5']
Run Code Online (Sandbox Code Playgroud)


Ant*_*ins 11

csv模块(标准库)会自动完成,虽然文档是不是非常具体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
Run Code Online (Sandbox Code Playgroud)


Sil*_*ost 9

for line in open(fname):
    line = line.split()
    line[-1] = line[-1].strip('"\n')
    floats = [float(i) for i in line]
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用内置模块,即打算完成这个任务.即csv:

>>> import csv
>>> for line in csv.reader(open(fname), delimiter=' '):
    print([float(i) for i in line])

[5.6, 4.5, 6.8, 6.5]
[5.6, 4.5, 6.8, 6.5]
Run Code Online (Sandbox Code Playgroud)


yu_*_*sha 7

或者您可以简单地更换您的线路

l = re.split("\s+",string.strip(line)).replace('\"','')
Run Code Online (Sandbox Code Playgroud)

有了这个:

l = re.split('[\s"]+',string.strip(line))
Run Code Online (Sandbox Code Playgroud)


Mas*_*yed 5

我本质上用来删除"in"25"使用

Code:
        result = result.strip("\"") #remove double quotes characters 
Run Code Online (Sandbox Code Playgroud)