【问题标题】:Python : split text to list of linesPython:将文本拆分为行列表
【发布时间】:2017-02-08 07:28:39
【问题描述】:

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

12345 | 6789 | abcd | efgh 

我希望我的输出是 Like :

12345
6789
abcd
efgh

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

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

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

我将不胜感激。

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

【问题讨论】:

  • 你得到的问题到底是什么错误?
  • 真正的代码是:f.readlines() 然后循环遍历它们,在 '|' 上拆分
  • Traceback (most recent call last): File "C:\Users\TOSHIBA\Desktop\findme.py", line 4, in <module> r = f.read() File "C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 529: character maps to <undefined>

标签: python text split lines


【解决方案1】:

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

  • f.read 没有读完整行。应该是f.readline()
  • splitlines的功能是什么?

您的问题在不同方面都不清楚。也许这个 sn-p 可能会有所帮助:

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

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

【讨论】:

  • 你的代码给了我那个错误Traceback (most recent call last): File "C:\Users\TOSHIBA\Desktop\csvfind.py", line 1, in <module> for line in open('contacts_index1.txt'): File "C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 529: character maps to <undefined>
  • 对不起,我的肉 line.split()
【解决方案2】:

我强烈建议将 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)

【讨论】:

  • 我也试过 CSV 但这里是错误Traceback (most recent call last): File "C:\Users\TOSHIBA\Desktop\csvfind.py", line 4, in <module> for row in reader: File "C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 529: character maps to <undefined>
【解决方案3】:

从您的所有 cmets 看来,问题似乎与文件中的实际文本有关,而不是解析它的能力。看来这里的每个人的解决方案都在正确的轨道上,你只需要强制编码。

您描述的错误描述为in this other StackOverflow 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")

【讨论】:

  • 你是对的兄弟。但它仍然给了我同样的错误,我不知道。我该怎么办!
  • 我也将文件保存为“UTF-8”,但仍然出现错误
  • 尝试该链接中的解决方案。您显示的错误使用编码“CP1252”加载。所以必须有一种方法可以强制它使用不同的编码(如 utf-8)读取。 import io io.open('contacts_index1.txt', encoding="utf-8")io.open('contacts_index1.txt', encoding="latin-1")
  • 另一种选择是告诉 Python 如果无法解码字符,则将其丢弃:io.open("contacts_index1.txt", errors="ignore")stackoverflow.com/questions/3284827/…
【解决方案4】:

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

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)

【讨论】:

  • 对不起,我不明白我到底想做什么?
  • 再次抱歉,但它给了我:Traceback (most recent call last): File "C:\Users\TOSHIBA\Desktop\hope.py", line 4, in <module> Contents = dataFunction("contacts_index1.txt") File "C:\Users\TOSHIBA\Desktop\hope.py", line 3, in dataFunction return f.read().decode('utf-8') File "C:\Users\TOSHIBA\AppData\Local\Programs\Python\Python35-32\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 529: character maps to <undefined>
  • 看看我更新了!如果不工作评论...!我想帮你!
  • 如果它不起作用检查 encoding="Latin-1" 事件也不起作用使用在线工具检查编码格式并更改第二个参数它将起作用......! @SamehWeangy
  • 我已经这样做了,并且出现了我评论的上部错误,我真的很感谢你试图做的兄弟。
【解决方案5】:

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

类似:

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())

【讨论】:

  • @dwg 谢谢,兄弟,它和一个一起工作。但另一个有编码问题。所以我仍然陷入解码这个问题。
  • 如果是编码问题,用合适的编解码器打开即可。
  • 我为使用你的脚本进行编码制作了另一种解决方案,现在它可以工作了。谢啦兄弟 。但是如果我需要将输出写入新文件而不是在 shell 中打印,我该怎么办,兄弟?
  • Python 2 还是 3?有所作为。 Python 2,在每一端使用encodedecode 作为here。 Python 3,使用嵌入在open中的编码器
  • 它是 python-3.5.0
猜你喜欢
  • 2018-08-25
  • 2021-07-24
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多