如何从Unicode(UTF-8)CSV文件导入numpy数组

发布于 2021-01-29 16:46:46

即时通讯不是要聪明或快速地做到这一点,而只是想做到这一点。

我有一个文件看起来像这样:

$ cat all_user_token_counts.csv  
@5raphaels,in,15
@5raphaels,for,15
@5raphaels,unless,11
@5raphaels,you,11

我知道它的未编码utf-8编码是因为我创建了它,就像这样

    debug('opening ' + ALL_USER_TOKEN_COUNTS_FILE)
    file = codecs.open(ALL_USER_TOKEN_COUNTS_FILE, encoding="utf-8",mode= "w")
    for (user, token) in tokenizer.get_tokens_from_all_files():
        #... count tokens ..
        file.write(unicode(username +","+ token +","+ str(count) +"\r\n"))

我想将其读取到一个numpy数组中,所以它看起来像这样或其他内容。

   array([[u'@5raphaels', u'in', 15],
          [u'@5raphaels', u'for', 11],
          [u'@5raphaels', u'unless', 11]], 
          dtype=('<U10', '<U10', int))

在我尝试编写此问题的过程中,我想到可能甚至不可能?如果是这样,我很想知道!

提前致谢!

关注者
0
被浏览
72
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    这可以通过np.loadtxt轻松完成

    import numpy as np
    arr=np.loadtxt('all_user_token_counts.csv',delimiter=',',
                      dtype = '|U10,<U10,int')
    print(arr)
    
    # [(u'@5raphaels', u'in', 15) (u'@5raphaels', u'for', 15)
    #  (u'@5raphaels', u'unless', 11) (u'@5raphaels', u'you', 11)]
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看