Python :将文本拆分为行列表

Python : split text to list of lines

我是 Python 的新手,但我的文本文件如下:

12345 | 6789 | abcd | efgh 

我希望我的输出像:

12345
6789
abcd
efgh

=====================

我真的不知道剧本 但是我用那些函数 split() , strip() 做了很多脚本,blame blame blame

但是我没有做到 所以我寻求帮助有人可以。

我将不胜感激任何帮助。

with open('contacts_index1.txt') as f:
    lines = f.read().splitlines("|")

您发布的代码存在一些问题:

  • f.read 没有读整行。应该是f.readline()
  • 函数是什么splitlines

你的问题在不同方面都不太清楚。也许这段代码可以提供一些帮助:

for line in open('contacts_index1.txt'):
    elements = line.split('|')
    for element in elements:
        print element.strip()

已编辑:我不知道函数 splitlines。刚刚查了一下。无论如何,您在代码中使用它的方式似乎都不正确。

我强烈建议为此类任务使用 csv 模块,因为它看起来像一个 csv 类型的文件,使用“|”作为分隔符:

import csv
with open('contacts_index1.txt','r') as f:
    reader=csv.reader(f,delimiter='|')
    for row in reader:
        #do things with each line
        print "\n".join(row)

从您的所有评论来看,问题似乎与文件中的实际文本有关,而不是解析它的能力。看来这里大家的解决方案都是对的,你只需要强制编码即可。

您描述的错误描述为 in this other Whosebug post

with open('contacts_index1.txt', 'r') as f:
     lines = f.read().encode("utf-8").replace("|", "\n")

编辑:这个问题似乎是一个没有正确解码的令人讨厌的字符。使用 open,您可以告诉它忽略无法解码的字符。

import io 
with io.open("contacts_index1.txt", errors="ignore") as f:
    lines = f.read()replace("|", "\n")

您将不得不使用解码。以下代码将起作用:

def dataFunction(filename):
    with open(filename, encoding="utf8") as f:
        return f.read()

以文件名作为参数调用此函数:

Contents = dataFunction(filename)
elements = Contents.split("|")
for element in elements:
         print(element)

请逐行执行此操作。无需一次读取整个文件。

类似于:

with open(file_name) as f_in:
    for line in f_in:
        for word in line.split('|'):
            print word.strip()

如果是 unicode 问题,大部分时间是自动的:

$ cat /tmp/so.txt
12345 | 6789 | abcd | éfgh 

(注意文件中的é

上面的程序有效。如果它不起作用,请使用编解码器:

with open(fn) as f_in:
    for line in f_in:
        line=line.decode('utf-8')  # or whatever codec is used for that file...
        for word in line.split('|'):
            print word.strip()

使用Python3,只需在打开文件时设置编码:

with open(fn, encoding='utf-8') as f_in:   # <= replace with the encoding of the file...
    for line in f_in:
        for word in line.split('|'):
            print(word.strip())