[英]Count how often a specific string occurs in a list
我想在一種“詞袋”方法中成對比較幾個列表。 我的名單中只有字符串。
不幸的是,我的腳本中有一個我無法修復的錯誤。
如果列表中有數字,代碼就可以工作,但只要列表中有字符串,它就不再運行了。 我感謝您的幫助。
我收到以下錯誤消息:
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
默認情況下, numpy.zeros
會生成一個空的浮點數組,使用你需要指定的字符串來指定dtype=str
:
bow_matrix = numpy.zeros(shape = (3, len_bow_matrix),dtype=str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.