[英]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”等)。 脚步
下面是代码,
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.