Tôi có một tệp .txt với cái này bên trong - 2.9, gardena ca
Những gì tôi đang cố gắng làm là chuyển đổi văn bản đó thành một .csv [bảng] bằng cách sử dụng tập lệnh Python:
import csv
import itertools
with open['log.txt', 'r'] as in_file:
stripped = [line.strip[] for line in in_file]
lines = [line for line in stripped if line]
grouped = itertools.izip[*[lines] * 3]
with open['log.csv', 'w'] as out_file:
writer = csv.writer[out_file]
writer.writerow[['title', 'intro']]
writer.writerows[grouped]
Đầu ra tôi nhận được trong tệp log.csv là - tiêu đề, giới thiệu, khẩu hiệu
Những gì tôi muốn tệp log.csv hiển thị là:
title,intro
2.9,Gardena CA
Được hỏi ngày 22 tháng 9 năm 2016 lúc 14:38Sep 22, 2016 at 14:38
6
Bạn cần chia dòng trước.
import csv
with open['log.txt', 'r'] as in_file:
stripped = [line.strip[] for line in in_file]
lines = [line.split[","] for line in stripped if line]
with open['log.csv', 'w'] as out_file:
writer = csv.writer[out_file]
writer.writerow[['title', 'intro']]
writer.writerows[lines]
Đã trả lời ngày 22 tháng 9 năm 2016 lúc 15:00Sep 22, 2016 at 15:00
Tom Yatestom YatesTom Yates
8917 Huy hiệu bạc11 Huy hiệu đồng7 silver badges11 bronze badges
3
import pandas as pd
df = pd.read_fwf['log.txt']
df.to_csv['log.csv']
Đã trả lời ngày 28 tháng 11 năm 2018 lúc 20:14Nov 28, 2018 at 20:14
KIT Starkkit StarkKit Stark
2112 Huy hiệu bạc3 Huy hiệu đồng2 silver badges3 bronze badges
2
Đây là cách tôi làm điều đó:
with open[txtfile, 'r'] as infile, open[csvfile, 'w'] as outfile:
stripped = [line.strip[] for line in infile]
lines = [line.split[","] for line in stripped if line]
writer = csv.writer[outfile]
writer.writerows[lines]
Hy vọng nó giúp!
Đã trả lời ngày 12 tháng 10 năm 2018 lúc 13:17Oct 12, 2018 at 13:17
iun1xiun1xiun1x
93310 Huy hiệu bạc12 Huy hiệu đồng10 silver badges12 bronze badges
Tôi Suposse Đây là đầu ra bạn cần:
title,intro,tagline
2.9,Gardena,CA
Nó có thể được thực hiện với những thay đổi này đối với mã của bạn:
import csv
import itertools
with open['log.txt', 'r'] as in_file:
lines = in_file.read[].splitlines[]
stripped = [line.replace[","," "].split[] for line in lines]
grouped = itertools.izip[*[stripped]*1]
with open['log.csv', 'w'] as out_file:
writer = csv.writer[out_file]
writer.writerow[['title', 'intro', 'tagline']]
for group in grouped:
writer.writerows[group]
Đã trả lời ngày 22 tháng 9 năm 2016 lúc 15:08Sep 22, 2016 at 15:08
Trong Python phiên bản 3.x, intertools.izip không hoạt động.
Mã chức năng cho Python 3 là:
import csv
import zlib
with open['output.txt', 'r'] as in_file:
lines = in_file.read[].splitlines[]
stripped = [line.replace[","," "].split[] for line in lines]
grouped = zip[*[stripped]*1]
with open['teste.csv', 'w'] as out_file:
writer = csv.writer[out_file]
writer.writerow[['A', 'B', 'C', 'D']]
for group in grouped:
writer.writerows[group]
Đã trả lời ngày 11 tháng 3 năm 2021 lúc 21:07Mar 11, 2021 at 21:07