Skip to main content
 首页 » 编程设计

python之如何将文本文件导入 Python 中的数组( Pyramid )

2025年05月04日12emanlee

你好,我正在尝试做一些非常简单的事情

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

我找到了 this和 this所以我导入了 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 调试:

请您参考如下方法:

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

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