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

后端 未结 9 2112
被撕碎了的回忆
被撕碎了的回忆 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 05:13

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

    Code:
            result = result.strip("\"") #remove double quotes characters 
    
    0 讨论(0)
  • 2020-12-29 05:21
    for line in open(fname):
        line = line.split()
        line[-1] = line[-1].strip('"\n')
        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]
    
    0 讨论(0)
  • 2020-12-29 05:21

    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']
    
    0 讨论(0)
提交回复
热议问题