0

我有一个输入文件,其中每一行都是 python 列表的形式。它看起来像这样:

['people', 'desert', 'snow']
['people', 'flower', 'garden', 'goat']

我想处理这个文件并从中删除所有标点符号,即“[”、“]”、“”和“'”

我正在使用以下代码:

import string
import re

openfile=open('jcn','r')
writefile=open('jcnout','w')
punctuation=["[","]",",","'"]

for line in openfile:
    line.translate(None, string.punctuation)
    writefile.write(line)

writefile.flush()
writefile.close()
openfile.close()

但它似乎不起作用,即标点符号保留在输出文件中。有人可以告诉我我错在哪里

4

2 回答 2

3

你需要改变

line.translate(None, string.punctuation)

line = line.translate(None, string.punctuation)

在 Python 中,字符串是不可变的。相应地,translate()不会更改字符串,而是返回翻译后的字符串(您将忽略它)。

于 2013-06-30T07:44:57.397 回答
0

要支持字符串的标点符号:

import ast
import fileinput

for line in fileinput.input(inplace=1): #NOTE: replace inplace
    print " ".join(ast.literal_eval(line))
于 2013-06-30T07:51:55.390 回答