English 中文(简体)
Can Python remove double quotes from a string, when reading in text file?
原标题:

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
问题回答
for line in open(name, "r"):
    line = line.replace( " ,   ).strip()
    a, b, c, d = map(float, line.split())

This is kind of bare-bones, and will raise exceptions if (for example) there aren t four values on the line, etc.

There s a module you can use from the standard library called shlex:

>>> import shlex
>>> print shlex.split( 5.6  4.5  6.8  "6.5" )
[ 5.6 ,  4.5 ,  6.8 ,  6.5 ]
for line in open(fname):
    line = line.split()
    line[-1] = line[-1].strip( "
 )
    floats = [float(i) for i in line]

another option is to use built-in module, that is intended for this task. namely 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]

Or you can simply replace your line

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

with this:

l = re.split( [s"]+ ,string.strip(line))

I used in essence to remove the " in "25" using

Code:
        result = result.strip(""") #remove double quotes characters 

I think the easiest and most efficient thing to do would be to slice it!

From your code:

d = l[3]
returns "6.5"

so you simply add another statement:

d = d[1:-1]

now it will return 6.5 without the leading and end double quotes.

viola! :)

You can use regexp, try something like this

import re
re.findall("[0-9.]+", file(name).read())

This will give you a list of all numbers in your file as strings without any quotes.

IMHO, the most universal doublequote stripper is this:

In [1]: s =  1 " 1 2" 0 a "3 4 5 " 6 
In [2]: [i[0].strip() for i in csv.reader(s, delimiter=   ) if i != [  ,   ]]
Out[2]: [ 1 ,  1 2 ,  0 ,  a ,  3 4 5 ,  6 ]




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签