-1

I have to remove quotes from a relatively large text file. I have looked at the questions that may have matched this one, yet I am still not able to remove the quotes from specific lines from the text file.

This is what a short segment from the file looks like:

1 - "C1".

E #1 - "C1".

2 - "C2".

1

2

E #2 - "C2".

I would like to have 1-"C1". be replaced by c1, and E #1 - "C1" be replaced with E c1. I tried replacing these in python, but I get an error because of the double "'s.

I tried:

input=open('file.text', 'r')
output=open(newfile.txt','w')
clean==input.read().replace("1 - "C1".","c1").replace("E #1 - "C1"."," E c1")
output.write(clean)

I have with sed:

sed 's\"//g'<'newfile.txt'>'outfile.txt'.

But yet another syntax error.

4

1 回答 1

0

If you're sure you want literal replacement, you just need to escape the quotes or use single quotes: replace('1 - "C1".', "c1") and so on (and to correct a couple of syntax-breaking typos). This, however, will only work on the first line, so there's no point in reading the whole file then. To do a smarter job, you could use re.sub:

with open('file.text') as input, open('newfile.txt','w') as output:
     for line in input:
         line = re.sub(r'^(?P<num>\d+) - "C(?P=num)".$',
                       lambda m: 'c' + m.groups()[0], line)
         line = re.sub(r'^E #(?P<num>\d+) - "C(?P=num)".$',
                       lambda m: 'E c' + m.groups()[0], line)
         output.write(line)

In the sed command you seem to try to simply remove the quotes:

sed 's/"//g' newfile.txt > outfile.txt
于 2012-06-23T15:18:58.010 回答