【问题标题】:Creating string based array introduces random 'b' before string创建基于字符串的数组在字符串之前引入随机“b”
【发布时间】:2018-01-16 07:57:11
【问题描述】:

我正在尝试创建一个基本上包含单词列表的表格。我更喜欢表格格式,因为它最终会进入 Excel。但是,通过我的代码,我不断在字符串之前引入字母“b”。任何帮助,将不胜感激。

我什至尝试在各个阶段进行打印,以了解它们被引入的位置和原因。 代码:

from xlwt import Workbook
import numpy as np

wb = Workbook()
Number_Of_Days = int(input('How many days do you want?'))
All_Sheets = np.chararray((Number_Of_Days,1))
All_Sheets = np.chararray(All_Sheets.shape, itemsize = 10)
All_Sheets[:] = ''

print(All_Sheets)

count = 0
while count < Number_Of_Days:
    Sheet_Name = input(print('Enter the name of day', count+1))
    All_Sheets [count,0] = Sheet_Name
    count = count + 1

print(All_Sheets)

Code and output

【问题讨论】:

  • 这表明您正在查看的是字节文字,而不是字符串:stackoverflow.com/questions/6269765/…
  • @Jeremy 感谢您的快速回复。无论如何我可以让我的输入成为一个字符串并在这种情况下记下一个字节文字?当我把它放进去时,excel会显示b'...'吗?还是会被忽略?
  • 这将有助于转换:stackoverflow.com/questions/606191/… 至于 Excel 会发生什么,我真的不确定。

标签: python arrays string list numpy


【解决方案1】:

注意chararray 文档:

chararray 类的存在是为了向后兼容 Numarray,不建议用于新开发。从 numpy 开始 1.4、如果需要字符串数组,建议使用数组 dtypeobject_string_unicode_,并使用免费功能 在numpy.char 模块中进行快速向量化字符串操作。

In [191]: np.chararray((2,1))
Out[191]: 
chararray([[''],
           [b'\x01']],
          dtype='|S1')

'|S1' dtype 表示一个字符的字节串。这是 Py2 中的默认类型,但在 Py3 中它被标记为 b 字符。

初始化字符数组的更好方法是:

In [192]: np.zeros((2,1), dtype='U10')
Out[192]: 
array([[''],
       ['']],
      dtype='<U10')

In [194]: np.zeros((2,1), dtype='S10')
Out[194]: 
array([[b''],
       [b'']],
      dtype='|S10')

甚至更好的字符串列表:

In [195]: np.array(['one','two','three'])
Out[195]: 
array(['one', 'two', 'three'],
      dtype='<U5')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    相关资源
    最近更新 更多