【问题标题】:Convert text document to numpy array of ASCII numbers in python在 python 中将文本文档转换为 ASCII 数字的 numpy 数组
【发布时间】:2018-06-10 02:28:09
【问题描述】:

我有一个包含字母、数字、空格和特殊字符等的大型纯文本文档 (UTF-8)。

我想将文本文档中的所有单个字符转换为数字,然后将文档表示为一个 numpy 数组。

我可以为此使用内置的 python ord() 函数吗?

我的理解是它返回一个表示字符的 Unicode 代码点的整数,但一次只接受一个字符,我想知道是否有更好的方法将大型文本文档转换为数字。

或者我可以使用 ord() 函数遍历整个文档吗?

编辑

我基本上想做这样的事情!但原生于 python https://www.browserling.com/tools/text-to-ascii

这是我目前拥有的

def convert_to_ascii(text):
    return ",".join(str(ord(char)) for char in text)

with open('test.txt', 'r') as myfile:
    data = myfile.read()

convert_to_ascii(data)

values = [int(i) for i in x.split(',')] 

array = np.array(values)

有没有更好的方法来做到这一点?

【问题讨论】:

    标签: python-3.x numpy utf-8 nlp ascii


    【解决方案1】:

    我一直在研究同样的问题,并且遇到了一种更简单、更快的技术,如下所示:

    import numpy as np
    
    text = 'abcABC00'
    
    letter_array = np.fromiter(text, dtype='c')
    letter_array.shape, letter_array.dtype
    
        ((8,), dtype('S1'))
    
    
    ascii_array = letter_array.view(np.int8)
    ascii_array.shape, ascii_array.dtype, ascii_array
    
        ((8,), dtype('int8'), array([97, 98, 99, 65, 66, 67, 48, 48], dtype=int8))
    

    我包含中间值只是为了显示发生了什么,但生产代码可以减少到一行。

    ascii_array = np.fromiter(text, dtype='c').view(np.int8)
    

    【讨论】:

    • 你最后的单行很好用,谢谢。我的 text 变量是一个 ndarray 切片。在该分配之后,ndarr1 = ndarr1.astype(numpy.int64) 将整个 ndarray 数字字符串更改为整数。
    【解决方案2】:

    您应该跳过",".join() 部分,因为这里没有必要。

    相反,您可以简单地在convert_to_ascii() 函数中创建values 列表:

    def convert_to_ascii(text):
        return [ord(char) for char in text)
    
    values = convert_to_ascii(data)
    array = np.array(values)
    

    然而,即使是中间列表也是不必要的,因为一个 numpy 数组可以从一个可迭代对象构造。如果您提前知道长度,它可以有效地做到这一点。而你做到了:这是字符串的长度。因此:

    def convert_to_ascii(text):
        for char in text:
            yield ord(char)
    
    array = np.fromiter(convert_to_ascii(data), count=len(data))
    

    并且这个convert_to_ascii函数可以替换为对内置map函数的调用:

    array = np.fromiter(map(ord, data), count=len(data))
    

    顺便说一句,如果你的文件是用 UTF-8 编码的,你应该可以用encoding="utf-8" 参数打开文件来确定。默认值取决于平台/区域设置。

    【讨论】:

      猜你喜欢
      • 2012-09-19
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 1970-01-01
      • 2018-02-18
      • 2018-08-28
      • 1970-01-01
      相关资源
      最近更新 更多