![](/img/trans.png)
[英]How to import data from .txt file to a specifc excel sheet with Python?
[英]Python script for pulling data from txt file to excel
這是我的文件:
例子.txt
new names_a
tim
jeremy; 24 - age
next
new "names_b"
jordan; 27 - age
alex; 26 - age
steven; 24 - age
next
new names_c
johnny; 20 - age
ron
;joe; 19 - age
brian; 23 - age
next
這是我的代碼:
file=open("example.txt", "r")
data=file.read()
categories=data.split('new')
dict_format={}
for categor_data in categories:
items=categor_data.split('\n')
item_name=items[0].replace(" ", "")
item_name=item_name.strip('"')
dict_format[item_name]=items[1:]
for name in dict_format:
print(name)
print("Which category to export?")
answer=input()
with open(answer+".csv",'w') as csv:
for row in dict_format[answer][:-1]:
if row != "":
csv.write(row.replace(";",",")+"\n")
csv.write(dict_format[answer][-1].replace(";",","))
csv.close()
類別 names_c 的示例輸出:
一個 | 乙 | C | |
---|---|---|---|
1 | 約翰尼 | 20 - 年齡 | |
2 | 羅恩 | ||
3 | 喬 | 19 - 年齡 | |
4 | 布萊恩 | 23 - 年齡 | |
5 | |||
6 | 下一個 |
問題一:
有沒有辦法:
a) 讓代碼不讀取單詞“next”作為列表的一部分
b)打開文件,刪除單詞'next'的所有條目,保存文件,關閉文件,重新打開文件然后運行代碼
問題2:
有沒有辦法不輸出以';'開頭的條目? 例如:;喬; 19 - 年齡
問題 3:
有沒有辦法刪除空行?
期望的輸出:
一個 | 乙 | C | |
---|---|---|---|
1 | 約翰尼 | 20 - 年齡 | |
2 | 羅恩 | ||
3 | 布萊恩 | 23 - 年齡 |
這是一種方法:
import pandas as pd
# Read data using Pandas
df = pd.read_csv('example.txt',sep = '\n+', header = None, engine='python')
# Drop rows starting with ';' (e.g. ;joe; 19 - age) and 'next'
df = df.drop(df[df[0].str.startswith((';','next'))].index)
# Split categories
df2 = df[0].str.replace('"','').str.split('new ',expand=True)
# Grop dataframe by categories
df3.fillna(method='ffill',inplace=True)
gp = df4.groupby(1)
dfs = [gp.get_group(x).reset_index().drop('index',axis=1).set_index(1)[0].str.split(';',expand=True).iloc[1:] for x in gp.groups]
# save dataframes
for df in dfs:
df.to_csv(f"{df.index[0]}.csv",index=False)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.