我有一个要求,我需要将我的文本文件转换为csv并使用python进行操作。我的文本文件如下所示,
Employee Name : XXXXX
Employee Number : 12345
Age : 45
Hobbies: Tennis
Employee Name: xxx
Employee Number :123456
Hobbies : Football
我希望我的CSV文件的列名称为员工姓名,员工编号,年龄和爱好,当特定值不存在时,它应该在该特定位置具有NA值。有任何简单的解决方案吗?提前致谢
答案 0 :(得分:0)
也许这有助于您入门?它只是第一个员工数据的静态输出。您现在需要将其包装到文件的某种迭代中。很可能是一个更优雅的解决方案,但如果没有单一的import语句,你就会这样做;)
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case android.R.id.home:
finish();
break;
}
return true;
}
答案 1 :(得分:0)
您可以这样做:
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
字段。
答案 2 :(得分:0)
我为此采取了非常简单的步骤,可能不是最佳的,但解决了问题。这里的重要案例我可以看到单个文件中可以有多个键(“员工姓名”等)。 步骤
以下是代码,
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
我希望这会有所帮助。