我正在尝试使用 Python 将数据从 .txt
文件转换为 .csv
文件。我的 .txt
文件目前的格式如下:
www.thing.com
Thing
2010
linkedin.com/company/thing
www.hello.com
Hello
1999
linkedin.com/company/hello
...
我想要一个程序来读取关于“Thing”的 4 行,并将其排成一行。然后,它将读取关于“Hello”的 4 行,并将其排成一行,每一项都与关于“Thing”的行在同一列中。
"www.thing.com,Thing,2010,linkedin.com/company/thing"
"www.hello.com,Hello,1999,linkedin.com/company/hello"
...
这是我目前所拥有的(不是很多):
import csv
text_file = open("document.txt", "r")
with open('output.csv', 'wb') as mycsv:
filewriter = csv.writer(mycsv)
mycsv.writerow(["company", "name", "date", "linkedin"])
for line in text_file:
URL = line
line = next(text_file)
name = line
line = next(text_file)
date = line
line = next(text_file)
LinkedIn = line
line = next(text_file)
mycsv.writerow(URL, name, date, LinkedIn)
到目前为止,我所查找的大多数文件已经将 .txt
文档格式化为每一行,但我的 .txt
中只有一行数据多行。
我将如何解决这个问题?
最佳答案
这是解决您的问题的另一种方法:
def group_data(table, n=4):
# Group your table's data by n elements
yield from [table[k: k + n] for k in range(0, len(table), n)]
def write_csv(file_name, data):
with open(file_name, 'a') as f:
# Loop over your grouped data
for elm in data:
# Write the grouped elemenets into a file
f.write(','.join(k for k in elm) + '\n')
a = '''www.thing.com
Thing
2010
linkedin.com/company/thing
www.hello.com
Hello
1999
linkedin.com/company/hello'''
data = [elm for elm in a.split('\n')]
grouped = group_data(data)
write_csv('csv_file.csv', grouped)
输出:
www.thing.com,Thing,2010,linkedin.com/company/thing
www.hello.com,Hello,1999,linkedin.com/company/hello
注意:如果您的数据不能按固定数字分组,那么您应该考虑一种新算法来获得您想要的输出。或者,您可以查看是否存在可用于进行分组的重复模式。否则,此当前代码将适用于您当前的文本片段。
关于python - 将包含多行数据的 .txt 转换为 .csv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54524801/