2012-06-23 41 views
-1

我必须从相对较大的文本文件中删除引号。我已经查看了可能与此相匹配的问题,但我仍然无法从文本文件中删除特定行中的引号。删除python中的文本文件中的引号

这是从文件中短段的样子:

1 - "C1". 

E #1 - "C1". 

2 - "C2". 

1 

2 

E #2 - "C2". 

我想有1-"C1"。替换为c1E #1 - "C1"替换为E c1。我试图在Python中替换这些,但由于双"'s,我得到一个错误。

我想:

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) 

我有SED:

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

但另一个语法错误。

+0

我第一次今天试过的东西,我从我的其他问题学会发布。 –

+0

这是input = open('file.text','r') –

+0

对不起,这个评论框正在翻阅我 –

回答

0

如果你确定要文字更换,你只需要逃避引号或者使用单引号:replace('1 - "C1".', "c1")等(并纠正了几个语法破错别字)。但是,这只能在第一行工作,所以在阅读整个文件时没有意义。做一个聪明的工作,你可以使用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) 

sed命令你似乎试图简单地去掉引号:

sed 's/"//g' newfile.txt > outfile.txt 
+0

谢谢......我确实使用过那样的sed命令。 –