2016-07-25 124 views
1

我正在从python中的文本文件中拆分单词。我收到了包含索引的行(c)和字典(word_positions)的数量。然后我创建一个零矩阵(c,index)。下面是代码:填充python矩阵

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 -the索引位置和count -The数连续计数单词

+0

目前还不清楚是什么你正在尝试做的。你能添加更多的解释/一个简单的例子吗? – Amoss

+0

如果你有一个行(字符串格式)名称'lines',你可以通过使用'len(lines.split())'(通过在每个空白处分割字符串所得到的数组的长度) – HolyDanna

+0

我在文本中有22行和254个独特的单词。所以这将是我的矩阵的大小,然后我只需要计算每个单词的行数为每个索引的独特单词,我有。现在更清晰了 – HalfPintBoy

回答

1

尝试下一个:

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 
0

看起来您正在尝试创建类似于n-dimensional list的内容。这些被嵌套列表里面自己这样实现的:

two_d_list = [[0, 1], [1, 2], [example, blah, blah blah]] 
words = two_d_list[2] 
single_word = two_d_list[2][1] # Notice the second index operator 

这个概念是非常灵活的Python和也可以嵌套在一个字典做,你想:

two_d_list = [{"word":1}, {"example":1, "blah":3}] 
words = two_d_list[1] # type(words) == dict 
single_word = two_d_list[2]["example"] # Similar index operator, but for the dictionary 

这实现了你想要的功能,但不使用语法matrix[c,index],但是这种语法在python中并不存在索引。方括号内的逗号通常描述列表文字的元素。相反,你可以用matrix[c][index] = count


访问行的字典中的元素您可以重载索引运算符来实现你想要的syntx。 Here是一个关于实现你想要的语法的问题。总结:

在列表类的包装中重载__getitem__(self, inex)函数,并将函数设置为接受元组。元组可以在没有括号创建,使语法matrix[c, index] = count