python - 如何制作计数向量 - Python
问题描述
如果我在字符串中有一个特定的单词,我想创建一个向量来计算字符串中的单词并将它们添加到向量中。
下面是我想要的一个例子。
word_list = ['a','b'] #this words of list is what I say 'specific word'.
以下列表中的列表是如果找到上述任何单词时要提取的列表。
[
['a', 'b', 'c']
['b', 'c', 'b']
['r', 'b', 'h']
['q', 'w', 'r']
['j', 'a', 'd']
['b', 'd', 'a']
]
我想要的结果就是这个。
word | a | b
-----------------
a | 0 | 2
b | 2 | 0
c | 0 | 2
d | 2 | 0
h | 0 | 1
j | 1 | 0
r | 0 | 1
我尝试进行一些编码,但我缺乏技能,而且处理我的所有数据太慢了。
以下是我对代码的尝试...
import pandas as pd
from konlpy.tag import Kkma
import numpy as np
test = pd.DataFrame(['a b c','b c b','r b h','q w r','j a d','b d a'],columns = ['txt'])
test_vec= []
for i in range(len(test)):
test_vec.append(operater.morphs(test['txt'][i]))
ext = ['a','b']
word = ['word']
result = pd.DataFrame([],columns = word + ext)
locate = 0
for i in range(len(test_vec)):
for j in range(len(ext)):
print('step0')
if ext[j] in test_vec[i]:
print('step1')
for k in range(len(test_vec[i])):
if test_vec[i][k] != ext[j]:
print('step2')
result.loc[locate] = np.nan
if np.size(np.where(result['word'] == result[ext[j]].loc[locate])) == 0:
result[ext[j]].loc[locate] = 1
result['word'].loc[locate] = test_vec[i][k]
else:
result[ext[j]].loc[locate] = result[ext[j]].loc[locate] + 1
locate = locate + 1
如果你知道一个快速和好的解决方案,如果你让我知道,我将不胜感激。
解决方案
推荐阅读
- c# - 从字符串转换为 int C# Windows 窗体
- python - 使用索引号查找字典键
- java - 根据每行中的第一个标记比较 2 个大文件的最佳方法是什么?
- excel - 如何识别范围和范围中的最后一个单元格并将绝对单元格地址插入 R1C1 公式?
- javascript - setState 函数不适用于子组件
- javascript - 捕获 $.getJSON().done() 中抛出的错误
- java - 如何抓住破管子的插座?
- r - `dplyr` 的 `summarize_all()` 在某些条件下
- sql - SQL - 将所有子项组合成一行
- node.js - 我如何将对象存储在全局数组或任何数据结构中,以便我可以在我的程序中像数据库一样使用该数组