簡體   English   中英

Python遍歷字典

[英]Python cycle through dict

我使用dict創建周期時遇到問題。 我有一本字典:鍵是唯一的數字,值是單詞。 我需要創建一個矩陣:行是句子的編號,列是單詞的唯一編號(來自dict)。 矩陣的元素將顯示每個句子中每個單詞的數量。 這是我創建dict的代碼。 (一開始我有一個帶有句子的原始文本文件)

with open ('sentences.txt', 'r') as file_obj:
    lines=[]
    for line in file_obj:
        line_split=re.split('[^a-z]',line.lower().strip()
        j=0
        new_line=[]
        while j<=len(line_split)-1:
            if (line_split[j]):
                new_line.append(line_split[j])
            j+=1            
        lines.append(new_line)    
    vocab = {}
    k = 1
    for i in range(len(lines)):
        for j in range(len(lines[i])):
            if lines[i][j] not in vocab.values():
                vocab[k]=lines[i][j]
                k+=1

import numpy as np  //now I am trying to create a matrix
matr = np.array(np.zeros((len(lines),len(vocab))))  
m=0
l=0
while l<22:
    for f in range (len(lines[l])):
        if vocab[1]==lines[l][f]:   //this works only for the 1 word in dict
            matr[l][0]+=1
    l+=1
print(matr[3][0])

matr = np.array(np.zeros((len(lines),len(vocab))))   // this also works
for values in range (len(vocab)):
    for line in lines:
        a=line.count(vocab[1])
        print(a)

但是,當我嘗試循環執行該命令時,沒有任何效果! 您能告訴我如何填寫整個矩陣嗎? 提前非常感謝您!

一些粗心的錯誤:第7行需要右括號, //不是Python語法。

查看您的代碼,我不知道您的一般算法是什么,只創建一個基本的字數字典。 因此,我提出了以下簡短的代碼:

import re
import sys

def get_vocabulary (filename):
  vocab_dict = {}

  with open (filename, 'r') as file_obj:
    for line in file_obj:
      for word in re.findall(r'[a-z]+',line.lower()):
        if word in vocab_dict:   # see below for an interesting alternative
          vocab_dict[word] += 1
        else:
          vocab_dict[word] = 1
  return vocab_dict

if len(sys.argv) > 1:
  vocab = get_vocabulary (sys.argv[1])
  for word in vocab:
    print (word, '->', str(vocab[word]))

請注意,我替換了您自己的

line_split=re.split('[^a-z]',line.lower().strip())

相反

re.findall(r'[a-z]+',line.lower())

因為您可以返回空元素,而我不會。 最初,我不得不添加一個if word:的測試if word:在將其插入字典之前,以防止添加大量的容器。 通過更好地檢查“單詞”,就不再需要了。

(使用Python的樂趣: if..else的替代方法看起來像這樣:

vocab_dict[word] = 1 if word not in vocab_dict else vocab_dict[word]+1

它的效率略低,因為vocab_dict[word]必須檢索兩次-您不能單獨說.. + 1 不過,這還是很不錯的一行。)

使用一些幫助 ,可以將字典轉換為“矩陣”(實際上是一個簡單的數組就足夠了)

matrix = [[vocab[word], word] for word in sorted(vocab)]
for row in matrix:
  print (row)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM