如何从txt文件中删除空元素

时间:2018-03-22 16:28:18

标签: python python-3.x

我想从txt文件副本中的字符串列表中删除空元素。 以前我按元素划分并将字符串a引导到小写字母。 关注点是从列表中删除空元素,代码不起作用。我试着编写一个函数,代码如下:

with open('text_file.txt','r') as rf:
    with open('text_file_copy.txt','w') as wf:
        for line in rf:
            line=line.lower() # lower case
            line=re.split(r'\s*', line) *# split elements by spaces*
            line=str(line)
            wf.write(line) *# writing to a file copy*
            line=wf.write(line)
            def empty_delete(line):
                new_line = []
                for word in line:
                    if word != '':
                        new_line.append(word)
                        return new_line
                    line=str(new_line)
                    wf.write(new_line) *# writing new list to a copy*

该文本仍有一些空元素: [' in',' compare',' to',' dogs,',' cats',&# 39;'' not','经历',' major','更改''在' ,'','驯化''流程。',''] [' in', '比较',','狗,','猫','有',' ;','经历','主要','更改',''''' ,'归化','流程。','']

1 个答案:

答案 0 :(得分:0)

以下是如何从可迭代(例如打开的文件)中删除空行和空行:

for line in ...:
   if not line or line.isspace():
     continue # Ignore this line
   # Do something usefule with the line.