我有一個包含類似以下信息的文件:更換的每個實例「 - 」從文件
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