使用python将文本文件转换为csv文件

2024-09-26 22:51:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个要求,我需要在我的文本文件转换成csv和使用python来做。我的文本文件是这样的

Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football

我希望我的CSV文件的列名为Employee Name、Employee Number、Age和hobients,当一个特定的值不存在时,它应该在那个特定的地方有一个值NA。有什么简单的解决办法吗?提前谢谢


Tags: 文件csvnamenumberage地方employeexxx
3条回答

也许这有助于你开始?它只是第一个雇员数据的静态输出。现在您需要将其包装成文件上的某种迭代。很有可能有一个更优雅的解决方案,但这是在没有一个import语句的情况下实现它的方法;)

with open('test.txt', 'r') as f:
    content = f.readlines()
    output_line = "".join([line.split(':')[1].replace('\n',';').strip() for line in content[0:4]])
    print(output_line)

你可以这样做:

records = """Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football"""

for record in records.split('Employee Name'):
    fields = record.split('\n')
    name = 'NA'
    number = 'NA'
    age = 'NA'
    hobbies = 'NA'
    for field in fields:
        field_name, field_value = field.split(':')
        if field_name == "": # This is employee name, since we split on it
            name = field_value
        if field_name == "Employee Number":
            number = field_value
        if field_name == "Age":
            age = field_value
        if field_name == "Hobbies":
            hobbies = field_value

当然,这个方法假设每个记录中至少有Employee Name字段。在

为此,我遵循了非常简单的步骤,可能不是最优的,但解决了问题。这里我能看到的重要情况是,在一个文件中可以有多个密钥(“雇员姓名”等)。 台阶

  1. 读取txt文件到行列表。在
  2. 将list转换成dict(逻辑可以更完善,或者可以在这里添加复杂的lambda)
  3. 只需使用pandas将dict转换为csv

下面是代码

import pandas

etxt_file = r"test.txt"
txt = open(txt_file, "r")
txt_string = txt.read()


txt_lines = txt_string.split("\n")
txt_dict = {}


for txt_line in txt_lines:
    k,v = txt_line.split(":")
    k = k.strip()
    v = v.strip()
    if txt_dict.has_key(k):
        list = txt_dict.get(k)
    else:
        list = []
    list.append(v)
    txt_dict[k]=list

print pandas.DataFrame.from_dict(txt_dict, orient="index")

输出:

^{pr2}$

我希望这有帮助。在

相关问题 更多 >

    热门问题