【问题标题】:Storing contents of a text file in an array [duplicate]将文本文件的内容存储在数组中[重复]
【发布时间】:2019-11-11 10:58:24
【问题描述】:

我有一个包含印地语文本行(大约 5400000 行)的文本文件。我想将这些行保存在 python 的字符串数组中。我试过这段代码:

    f = open("cleanHindi_Translated.txt" , "r")
    array = []
    for line in f:
        array.append(line)

    print(array)

但我收到一个错误:

    Traceback (most recent call last):
  File "hindi.py", line 11, in <module>
    for line in f:
  File "C:\Users\Preeti\AppData\Local\Programs\Python\Python37\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 0x8d in position 124: character maps to <undefined>
PS C:\Users\Preeti\Downloads\Compressed> python hindi.py
Traceback (most recent call last):
  File "hindi.py", line 11, in <module>
    for line in f:
  File "C:\Users\Preeti\AppData\Local\Programs\Python\Python37\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 0x8d in position 124: character maps to <undefined>

我不明白我在这里做错了什么。

【问题讨论】:

  • 以前没有尝试过类似的东西,但我想应该是.append(line)
  • 我试图包含: encoding="utf8" 但我无法包含读取模式 - 在这种情况下为“r”。所以我不认为这是该问题的重复,因为那里给出的解决方案对我不起作用。
  • 是的,我确实尝试过,但最终得到了类似的错误。
  • 编辑问题以显示您的其他尝试。 open 肯定需要编码,而你的错误信息显示编码错误。

标签: python text-files


【解决方案1】:

'lines' 是您要查找的数组(列表)

import io
with io.open('my_file.txt','r',encoding='utf-8') as f:
   lines = f.readlines()

【讨论】:

  • 我仍然收到错误Traceback (most recent call last): File "hindi.py", line 9, in &lt;module&gt; lines = f.readlines() File "C:\Users\Preeti\AppData\Local\Programs\Python\Python37\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 0x8d in position 124: character maps to &lt;undefined&gt;
  • @PraveenIyer 我已经更新了代码。
  • 这段代码似乎可以工作,但是当我尝试 print(lines) 时,我得到的输出中带有问号而不是印地文文本。
  • 非常感谢您,这似乎有效。我会尝试把这一切放在一起,得到我想要的结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-06
  • 1970-01-01
  • 1970-01-01
  • 2019-02-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
相关资源
最近更新 更多