我有一个类似
的文件1::12::33::1555
1::412::1245::23444
等等。我需要摆脱最后一个参数,并用逗号替换冒号。我试过了:
myfile = open('words.txt', 'r')
content = myfile.read()
content = re.sub(r'(.+)::(.+)::(.+)::(.+)', "\1,\2,\3", content)
myfile = open('words.txt', 'w')
myfile.write(content)
# Close the file
myfile.close()
但后面引用不起作用,我最后得到一个带逗号的文件..
我希望实现的目标是:
1,12,33
1,412,1245
答案 0 :(得分:6)
反向引用只会使用原始字符串进行插值。
re.sub(r'(.+)::(.+)::(.+)::(.+)', r"\1,\2,\3", content)
您也可以使用纯粹的字符串/列表
来完成此操作"\n".join([",".join(y.split('::')[:-1]) for y in content.split("\n")])
答案 1 :(得分:2)
您可以像CSV library那样使用(为简单起见,嵌入CSV):
import StringIO
import csv
t = """1::12::33::1555
1::412::1245::23444"""
f = StringIO.StringIO(t)
reader = csv.reader(f, delimiter=':')
for row in reader:
print ",".join(row[0:-1:2])
输出:
1,12,33
1,412,1245
答案 2 :(得分:1)
你能使用简单的字符串函数吗?
line = '1::412::1245::23444'
s = s.replace('::',',')
# content stored in a list
content = s.split(',')[:-1]
答案 3 :(得分:1)
在Python 2.6中:
with open('words.txt', 'r') as in_file:
with open('words_out.txt', 'w') as out_file:
for line in in_file:
new_line = ','.join(line.split('::')[:-1]) + ','
out_file.write(new_line)
在Python 2.7>中
with open('words.txt', 'r') as in_file, open('words_out.txt', 'w') as out_file:
for line in in_file:
new_line = ','.join(line.split('::')[:-1]) + ','
out_file.write(new_line)
答案 4 :(得分:1)
这会为您提供所需的字符串:
line = '1::412::1245::23444'
line_list = line.split('::')
new_line = ','.join(line_list[:-1])
print new_line
>> 1,412,1245
答案 5 :(得分:0)
看起来你真的不需要正则表达式。我要做的是使用::
作为分隔符拆分行,然后删除最后一项并重新插入逗号。
myfile = open('words.txt', 'r')
content = myfile.read()
numbers = [int(s) for s in content.split("::")] #get a list of numbers from the string
numbers = numbers[0:-1] #drop last number
content = "".join([str(n) + ",," for n in numbers]) #coalesce numbers back to string
myfile = open('words.txt', 'w')
myfile.write(content)
myfile.close()