我正在从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数连续计数单词
目前还不清楚是什么你正在尝试做的。你能添加更多的解释/一个简单的例子吗? – Amoss
如果你有一个行(字符串格式)名称'lines',你可以通过使用'len(lines.split())'(通过在每个空白处分割字符串所得到的数组的长度) – HolyDanna
我在文本中有22行和254个独特的单词。所以这将是我的矩阵的大小,然后我只需要计算每个单词的行数为每个索引的独特单词,我有。现在更清晰了 – HalfPintBoy