如何将这段代码的结果保存为.csv格式?
import re
import CSV
text = open('example.txt').read()
pattern = r'([0-9]+)[:]([0-9]+)[:](.*)'
regex = re.compile(pattern)
for match in regex.finditer(text):
result = ("{},{}".format(match.group(2),match.group(3)))
答案 0 :(得分:0)
如果我正确理解了您的问题,则可以按以下方式生成CSV:
import re
text = open('example.txt').read()
pattern = r'([0-9]+)[:]([0-9]+)[:](.*)'
regex = re.compile(pattern)
with open('csv_file.csv', 'w') as csv_file:
# Add header row with two columns
csv_file.write('{},{}\n'.format('Id', 'Tile'))
for match in regex.finditer(text):
result = ("{},{}".format(match.group(2),match.group(3)))
csv_file.write('{}\n'.format(result))