【问题标题】:Text to columns to array文本到列到数组
【发布时间】:2018-04-13 00:15:01
【问题描述】:

我一直在练习用 Python 阅读文件,因为我是那个特定领域的新手。

我有一个文本文件,例如:

Hello,my,name,is,Jack

我想像这样将它转移到list

["Hello", "my", "name", "is", "Jack"]

我试过这样做:

array = []
file = open("Names.txt", "r")
for line in file:
    array.append(line.split(","))
print(array)

但我得到了一个非常奇怪的error

File "C:\Python27\lib\random.py", line 261, in choice
return seq[int(self.random() * len(seq))]  # raises IndexError if seq is
empty
IndexError: list index out of range
>>>

我该如何解决?

【问题讨论】:

  • 这里的代码似乎不是错误所在。您是否在代码中的任何时候调用random.choice
  • 这个错误看起来像是来自代码中的其他地方。
  • 这可能与您声明随机 int 的方式有关。你自己声明 seq 吗?
  • @PatrickHaugh 不,我没有,错误来自 python 库,它似乎是“C:\Python27\lib\random.py”,第 261 行。不知道为什么,我什至没有碰过它。

标签: python list file


【解决方案1】:

您还没有发布您的完整代码(如在此代码中,您没有使用random module),但从error 可以看出您正在尝试在random.choice 上做一个空的list

您可以像这样复制error

>>> import random
>>> random.choice([])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/random.py", line 275, in choice
    return seq[int(self.random() * len(seq))]  # raises IndexError if seq is empty
IndexError: list index out of range

因此,如果您发布 整个 代码,我们可以进一步帮助您,但否则您需要找到您调用 random.choice() 的位置并调试您调用的 list 是什么

【讨论】:

    【解决方案2】:

    尝试以下方法:

    with open('Names.txt', 'rb') as f:
         content = list()
         for line in f:
              content.append(line.replace('\n','').split(','))
    

    如果您使用的是 Windows 操作系统,请在替换语句中使用 '\n\r' 而不是 '\n'

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-22
      • 1970-01-01
      • 2013-02-15
      • 1970-01-01
      相关资源
      最近更新 更多