簡體   English   中英

將部分txt文件提取到excel的腳本

[英]Script to extract part of txt file to an excel

我有一個看起來像這樣的 txt 文件:

category test_1

    aaa.com; test info - tw
    bbb.com; test info - al

category “test_2”

    ccc.com; test info - al
    ddd.com; test info - tw
    eee.com; test info - tw

category test_3

    fff.com
    ggg.com; test info - al
    hhh.com; test info - tw
    iii.com; test info - al

我需要幫助編輯一個 Python 腳本,該腳本提取 txt 文件的一部分並將其導出到 excel 文件。 例如,如果我想導出 test_1 類別中的條目,腳本將在 excel 文件中生成以下輸出。

一個 C
1 aaa.com 測試信息 - tw
2 bbb.com 測試信息 - al
3

我嘗試使用下面的代碼

我的 txt 文件作為 autotest.txt 保存在我的桌面上


file=open(“autotest.txt”,’r’)
data=file.read()
categories=data.split(‘category’)
dict_format={}
for categor_data in categories:
    items=categor_data.split(‘\n’)
    dict_format[items[0].replace(“ “, “”)=items[1:]

for name in dict_format:
    print(name)

print(“Which category to export to .csv?”)
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()

當我運行此代碼時,它可以正常工作並為 test_1 和 test_3 返回一個 excel 文件,但“test_2”不返回文件。 我不確定為什么會發生這種情況,因為我正在考慮並在包括引號的問題中輸入“test_2”。 我也試過在沒有的問題中輸入它並獲取一個文件,但它不包含條目。

非常感謝有關引號為何導致此錯誤的任何幫助。

謝謝!

打印密鑰時:

print(dict_format.keys())

返回:

dict_keys([“, ‘test_1’, ‘“test_2”’, ‘test_3’])

改變:

dict_format[items[0].replace(“ “, “”)]=items[1:]

對此:

item_name=items[0].replace(“ “, “”)
item_name=item_name.strip(‘“‘)
dict_format[item_name]=items[1:]

這會改變程序讀取類別並產生預期輸出的方式。

暫無
暫無

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

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