计算特定字符串在列表中出现的频率

时间:2016-08-23 20:03:18

标签: python string list numpy

我想在一种“词袋”方法中成对比较几个列表。我的名单中只有字符串 不幸的是,我的剧本中有一个我无法解决的错误 如果列表中有数字,代码就可以工作,但只要列表中有字符串,它就不再运行了。感谢您的帮助。

我收到以下错误消息:

Traceback (most recent call last):
File "test.py", line 21, in <module>
bow_matrix[0, p] = list_words_ab[p]
ValueError: could not convert string to float: 'd'

我的代码:

a = ["a", "b", "c", "d"]
b = ["b", "c", "d", "e"]

p = 0
if len(a) > len(b):
    max_words = len(a)
else:
    max_words = len(b)
list_words_ab = list(set(a) | set(b))
len_bow_matrix = len(list_words_ab)
bow_matrix = numpy.zeros(shape = (3, len_bow_matrix))

while p < len_bow_matrix:
    bow_matrix[0, p] = list_words_ab[p]
    p = p+1
p = 0
while p < len_bow_matrix:
    bow_matrix[1, p] = a.count(bow_matrix[0, p])
    bow_matrix[2, p] = b.count(bow_matrix[0, p])
    p = p+1

1 个答案:

答案 0 :(得分:3)

默认情况下numpy.zeros创建一个空的浮点数组,使用你需要指定的字符串dtype=str

bow_matrix = numpy.zeros(shape = (3, len_bow_matrix),dtype=str)