python - 填充 python 矩阵

标签 python arrays numpy matrix

我正在用Python从文本文件中分割单词。我收到了行数 (c) 和带有索引的字典 (word_positions)。然后我创建一个零矩阵(c,索引)。这是代码:

from collections import defaultdict
import re
import numpy as np

c=0

f = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r')

for line in f:
    c = c + 1

word_positions = {}

with open('/Users/Half_Pint_Boy/Desktop/sentenses.txt', 'r') as f:
    index = 0
    for word in re.findall(r'[a-z]+', f.read().lower()):
        if word not in word_positions:
            word_positions[word] = index
            index += 1
print(word_positions)

matrix=np.zeros(c,index)

我的问题:如何填充矩阵才能得到:matrix[c,index] = count,其中c - 是行数, index - 索引位置和 count - 一行中计数的单词数

最佳答案

下一步尝试:

import re
import numpy as np
from itertools import chain

text = open('/Users/Half_Pint_Boy/Desktop/sentenses.txt')

text_list = text.readlines()

c=0

for i in range(len(text_list)):
    c=c+1

text_niz = []

for i in range(len(text_list)):
    text_niz.append(text_list[i].lower()) # перевел к нижнему регистру

slovo = []

for j in range(len(text_niz)):
    slovo.append(re.split('[^a-z]', text_niz[j])) # токенизация

for e in range(len(slovo)):

    while slovo[e].count('') != 0:
        slovo[e].remove('') # удалил пустые слова

slovo_list = list(chain(*slovo))
print (slovo_list) # составил список слов

slovo_list=list(set(slovo_list)) # удалил повторяющиеся
x=len(slovo_list)

s = []

for i in range(len(slovo)):
    for j in range(len(slovo_list)):
        s.append(slovo[i].count(slovo_list[j])) # посчитал количество слов в каждом предложении

matr = np.array(s) # матрица вхождений слов в предложения
d = matr.reshape((c, x)) # преобразовал в матрицу 22*254

关于python - 填充 python 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38566995/

相关文章:

python - 使用 Python 检查文件是否为 CSV 格式

c++ - 获取所有数组的结构列表并自动检测每个数组的名称并打印它

arrays - 获取Scheme中向量的第一个元素

python - 如何从多种数据类型的组合 csv 中将数据过滤到独特的 pandas 数据框中?

python - 在 Python 中从日期时间获取日期

python - 从 ctypes windll 获取错误信息

python - 删除重复的行,无论项目订单 Pandas 如何

java - 将 int 数组添加到 2d ArrayList

python - 矢量化(手动)正向替换

python - 什么是西格玛裁剪?你怎么知道什么时候应用它?