如何从分割线python将字符串放入表中

时间:2017-01-29 15:08:49

标签: 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])没有打印任何内容!

谢谢你的帮助

1 个答案:

答案 0 :(得分:0)

错误在于:

tab[i] = div_texts[i]

选项卡为空,因此使用其第i个索引会导致一个仍未报告的IndexError异常,因为此代码位于try:块内,会捕获此类异常,因此控制流会立即转到except:子句。

例如,尝试使用tab.append(div_texts[i])