Can Python remove double quotes from a string, when reading in text file?

后端 未结 9 2111
被撕碎了的回忆
被撕碎了的回忆 2020-12-29 04:30

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 t

相关标签:
9条回答
  • 2020-12-29 04:56

    Or you can simply replace your line

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

    with this:

    l = re.split('[\s"]+',string.strip(line))
    
    0 讨论(0)
  • 2020-12-29 04:56

    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.

    0 讨论(0)
  • 2020-12-29 05:01
    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.

    0 讨论(0)
  • 2020-12-29 05:03

    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']
    
    0 讨论(0)
  • 2020-12-29 05:06

    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
    
    0 讨论(0)
  • 2020-12-29 05:06

    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! :)

    0 讨论(0)
提交回复
热议问题