Python One-hot 对文本中的每 2 个字符进行编码

标签 python dictionary text slice one-hot-encoding

我有一个自定义字母表,因为字典由 2 个字母键和相应的十进制值组成。我基本上想使用这个字母表对文本中的每 2 个字符进行编码。文本不能超出给定的字母表,因此手动定义它是安全的。这是我到目前为止所做的。

values = {'00' : 0.0, '01': 1.0, '02':2.0, '03':3.0, '04':4.0, '05':5.0, '06':6.0, '07':7.0, '08':8.0, '09':9.0, '0a':10, '0b':11, '0c':12, '0d':13, '0e':14}

sample = '000a'
indexes = [values[ch:ch+2] for ch in range(0,len(sample),2)]

输出应该是 0.010

但是,我在运行时遇到了 unhashable type: 'slice' 类型错误。

有没有另一种方法可以遍历文本中的每两个项目并将它们替换为字典中的值?或者对于超过 20G+ 的文本文件执行此操作的最佳方法是什么?

最佳答案

这会执行您在示例中描述的操作:

values = {'00' : 0.0, '01': 1.0, '02':2.0, '03':3.0, '04':4.0, '05':5.0, '06':6.0, '07':7.0, '08':8.0, '09':9.0, '0a':10, '0b':11, '0c':12, '0d':13, '0e':14}

sample = '000a'
indexes = ''.join(str(values[sample[ch:ch+2]]) for ch in range(0,len(sample),2))

我想你错过了 sample[:] for values keys...

关于Python One-hot 对文本中的每 2 个字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253061/

相关文章:

c# - Dictionary<TKey, TSource> 的神秘行为

c# - 使用字典进行重复数据删除的更好方法?

text - 为什么 LaTeX 会忽略文档类中的字体大小

html - 使文本重叠到 1px 水平线

Python:排序的文件列表

python - 从 CSV 文件中计算男性和女性的数量

python - 将多个列表映射到字典

python - 如何确定单词的概率?

python - 在 python 中为外语(希伯来语)创建 wordcloud

python - 使用 pandas/python 格式化 txt 文件