2

嗨所以我正在尝试做一些非常简单的事情

我有Array大量的句子被随机用于 slideDown 通知 div。因为我不想在 PyCharm 中有很长的 1 行,所以我想我可以将句子从 txt 文件导入到我的Array.

我发现了这个这个,所以我导入了numpy,并使用下面的代码,但是,它在行上中断(并跳到我的错误消息)success_msgs,我也没有收到错误。

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."]

有什么想法吗?:(


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

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._

在此处输入图像描述

调试器
在此处输入图像描述

我的 def genfromtxt

def genfromtxt(fname, dtype=float, comments='#', delimiter=None,
           skiprows=0, skip_header=0, skip_footer=0, converters=None,
           missing='', missing_values=None, filling_values=None,
           usecols=None, names=None,
           excludelist=None, deletechars=None, replace_space='_',
           autostrip=False, case_sensitive=True, defaultfmt="f%i",
           unpack=None, usemask=False, loose=True, invalid_raise=True):

genfromtxt 调试:

在此处输入图像描述

4

1 回答 1

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.']
于 2013-09-13T20:58:33.067 回答