1

我有一个看起来像的文件

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
4

6 回答 6

7

反向引用只会用原始字符串进行插值。

re.sub(r'(.+)::(.+)::(.+)::(.+)', r"\1,\2,\3", content)

您也可以使用纯字符串/列表来执行此操作

"\n".join([",".join(y.split('::')[:-1]) for y in content.split("\n")])
于 2013-04-30T21:53:23.767 回答
2

您可以像这样使用CSV 库(为简单起见嵌入 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
于 2013-04-30T22:00:56.190 回答
1

你可以只使用简单的字符串函数吗?

line = '1::412::1245::23444'
s = s.replace('::',',')
# content stored in a list
content = s.split(',')[:-1]
于 2013-04-30T21:55:01.197 回答
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)
于 2013-04-30T22:00:17.470 回答
1

这将为您提供所需的字符串:

line = '1::412::1245::23444'
line_list = line.split('::')
new_line = ','.join(line_list[:-1])

print new_line
>> 1,412,1245
于 2013-04-30T22:00:28.447 回答
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()
于 2013-05-01T02:36:57.910 回答