簡體   English   中英

使用python將文本文件轉換為csv文件

[英]Converting a text file into csv file using 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和Hobby,並且當不存在特定值時,該位置應具有NA值。 有任何簡單的解決方案嗎? 提前致謝

也許這可以幫助您入門? 這只是第一批員工數據的靜態輸出。 您現在需要將其包裝到文件的某種迭代中。 非常有可能是更優雅的解決方案,但是這就是您不使用單個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字段。

為此,我遵循了非常簡單的步驟,雖然不是最佳方法,但可以解決問題。 我在這里看到的重要情況是,單個文件中可以有多個鍵(“ Employee Name”等)。 腳步

  1. 讀取txt文件到行列表。
  2. 將列表轉換為dict(可以進一步改善邏輯或可以在此處添加復雜的lambda)
  3. 只需使用熊貓將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")

輸出:

                      0         1
Employee Number   12345    123456
Age                  45      None
Employee Name     XXXXX       xxx
Hobbies          Tennis  Football

我希望這有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM