如何在Python中将文本文件导入数组(金字塔)

时间:2013-09-13 20:54:52

标签: python arrays numpy text-files pyramid

嗨,所以我想做一些非常简单的事情

我有一个Array,其中有大量的句子被随机用于slideDown通知div。由于我不想在PyCharm中有一个非常长的1行,我想我可以将txt文件中的句子导入我的Array

我找到了thisthis,因此我导入了 numpy ,然后使用下面的代码,它中断了( <{1}}行上跳过我的错误消息,我也没有收到错误。

success_msgs

有什么想法? :(


我的文本文件(与py文件位于同一文件夹中:

def create_request(self):
    # text_file = open("success_requests.txt", "r")
    # lines = text_file.readlines()
    # print lines

    success_msgs = loadtxt("success_request.txt", comments="#", delimiter="_", unpack=False)
    #success_msgs = ['The intro request was sent successfully', "Request sent off, let's see what happens!", "Request Sent. Good luck, may the force be with you.", "Request sent, that was great! Like Bacon."]

enter image description here

调试器
enter image description here

我的def genfromtxt

The intro request was sent successfully_
Request sent off, let's see what happens!_
Request Sent. Good luck, may the force be with you._
Request sent, that was great! Like Bacon._

genfromtxt debug:

enter image description here

1 个答案:

答案 0 :(得分:1)

首先,告诉它使用带有dtype='S72'的字符串dtype(或者您期望的任何最大字符数)。

In [368]: np.genfromtxt("success_request.txt", delimiter='\n', dtype='S72')
Out[368]: 
array(['The intro request was sent successfully_',
       "Request sent off, let's see what happens!_",
       'Request Sent. Good luck, may the force be with you._',
       'Request sent, that was great! Like Bacon._'], 
      dtype='|S72')

或者,如果每一行以下划线结尾,并且您不想包含下划线,则可以设置delimiter='_'usecols=0以仅获取第一列:

In [372]: np.genfromtxt("success_request.txt", delimiter='_', usecols=0, dtype='S72')
Out[372]: 
array(['The intro request was sent successfully',
       "Request sent off, let's see what happens!",
       'Request Sent. Good luck, may the force be with you.',
       'Request sent, that was great! Like Bacon.'], 
      dtype='|S72')

但是没有理由不在不使用numpy和

的情况下加载文件
In [369]: s = open("success_request.txt",'r')

In [379]: [line.strip().strip('_') for line in s.readlines()]
Out[379]: 
['The intro request was sent successfully',
 "Request sent off, let's see what happens!",
 'Request Sent. Good luck, may the force be with you.',
 'Request sent, that was great! Like Bacon.']