简体   繁体   English

如何将 TXT 转换为 CSV?

[英]How to convert TXT to CSV?

I need your help.我需要你的帮助。 I have a text file, which is a database.我有一个文本文件,它是一个数据库。 The data in it looks something like this:其中的数据如下所示:

Anastasia [ID: 257949614] requested statistics for Russia - (13:48:37, 17.03.2020)
Alina [ID: 541327376] requested statistics for Russia - (13:50:45, 17.03.2020)
Alina [ID: 541327376] requested statistics for USA - (13:51:10, 17.03.2020)
Alina [ID: 541327376] requested statistics for Egypt - (13:51:50, 17.03.2020)
lofi [ID: 605986150] requested statistics for Montenegro - (13:51:58, 17.03.2020)

I need to convert it to CSV, while putting different data types in separate cells.我需要将其转换为 CSV,同时将不同的数据类型放在不同的单元格中。 Something like this:像这样的东西:

在此处输入图片说明

Step 1 - create a function that receives a text line and splits it to string however you like.第 1 步 - 创建一个接收文本行并将其拆分为字符串的函数。 There is not short way to do it because your original file is regular text.没有捷径可走,因为您的原始文件是常规文本。 For instance:例如:

def split_line(l):
  name = l[:l.find(' ')]
  l = l[len(name) + 1]
  id = l[:l.find(']')+1]
  l = l[len(id) + 1:]
  # ...
  return name, id, # ...

Step 2 - convert text file to list of lists (or tuples, in my case):第 2 步 - 将文本文件转换为列表(或元组,在我的情况下):

with open(input_file) as f:
  lines = [split_line(x) for x in f]

Step 3 - use the csv module.第 3 步 - 使用csv模块。

import csv
with open(output_file, 'w') as f:
  writer = csv.writer(f)
  writer.writelines(lines)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM