我有一个包含类似以下信息的文件:更换的每个实例“ - ”从文件
1/1/2010
1-2-3-4
1
1/2/2010
1-5-6-7
111
etc.
我希望能够写这其中'-'
每个实例都替换为另一个文件','
。我一直在使用str.split('-')
尝试并实现收到此错误
TypeError: must be string or read-only character buffer, not list
我也使用str.replace('-', 'i')
尝试后,我不能写一个列表文件,但所有这一切给了我另外一个错误
TypeError: replace() takes at least 2 arguments (1 given)
任何人都可以点我在正确的方向?
我还要指出,我试图首先使用str.split()
的原因是因为这最终都将被放入一个字典,像这样
{0:[['1/1/2010], ['1', '2', '3', '4'], ['1']], 1: [['1/2/2010'], ['1', '5', '6', '7'], ['111']], etc.}
只是一个更新... 我发现使用未提及的正则表达式执行此操作的简单方法。
>>> def test(filename):
import re
input_file = open(filename, 'r')
output_file = open('test.txt', "w")
for line in input_file:
line = line.strip()
line = re.sub('-', ',', line)
output_file.write(line)
output_file.write('\n')
input_file.close()
output_file.close()
这是否被集成到另一个程序中?你需要为这一步使用python吗?如果不是为什么不是shell命令:cat file | “tr” - “”,“ – Benedict 2012-02-03 18:43:06