簡體   English   中英

如何將字符串從分割線python放入表中

[英]How to put string into table from a splitted line python

我有一個讀取文件並拆分每一行的代碼,如果將兩個元素放在一個新表中,其中每個表元素由兩個拆分元素組成,對象是這樣的:

tab = [
    ('football', 'sport'),
    ('element!', 'pyhsics'),
    ('coefficient', 'math'),
    ....
]

我的文件由行組成,每行包含兩個由制表符分隔的元素

sport   football
Math    thermalization
Process thermalization
phsycis semi-classical methods
Process nuclear reactions

我的代碼是:

from codecs import open
from contextlib import suppress
import logging

new_path = 'C:/learning/file'
new_days = open(new_path,'w')

div_texts = []
tab= []


with open("C:/learning/clea", "r", "utf-8") as f:
    lines = f.readlines()
    f.close()

for line in lines:
    div_texts.append(line.strip().split("\t"))



for i in range(len(div_texts)):
    try:
        new_days.write(div_texts[i][0])
        tab[i] = div_texts[i]
        print(tab[i])
        new_days.write("\n")
    except (UnicodeEncodeError,KeyError,IndexError):
        pass

這里 print(tab[i]) 沒有打印任何東西!

感謝您的幫助

錯誤在這里:

tab[i] = div_texts[i]

tab 為空,因此取其第 i 個索引會導致 IndexError 異常,該異常仍未報告,因為此代碼位於try:塊中,可捕獲此類異常,因此控制流立即轉到except:子句。

例如,嘗試使用tab.append(div_texts[i])代替。

暫無
暫無

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

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