2017-12-02 6 views
0

pythonでtrain関数が正しく機能するようになっている問題があります。私はdef関数を変更することはできません。私はPosListのために一度に1行ずつ2番目のファイルを読み込む必要があるので、OpenPosのmovieWordCount [z]の値と一致させる必要があります。ファイルがある場合は、2桁目の行(スペースで区切られたもの)の1桁目を2桁目に入力すると良いです。そうでなければ、ファイルの最後に追加する必要があります。それは動作しません。値が見つからない場合は値を追加しません。値が存在する場合は値が見つかるかどうかわかりません。私は2日働いているthsiを取得して立ち往生している。ここでファイルを開き、データをファイルに保存するためのPythonコーディング

は、私が働いている私のコードセグメントである:ここで

with open("PosList") as OpenPos: 
    lines = OpenPos.readlines() 
    print lines 
    if movieWordCount[z] in lines: 
     print "found" 

    #Now use tokenize to split it apart by space and set to new array for me to call column2 
    else: 
     print "not found" 
     lines.append(movieWordCount[z] + " 1" + "\n") 

は私の完全なコードです:

#!/usr/bin/python 

#Import Counter 
import collections 
from collections import Counter 
#Was already here but pickle is used for data input and export 
import math, os, pickle, re 

class Bayes_Classifier: 

def __init__(self, trainDirectory = "movie_reviews/"): 

    #If file listing exists skip to train 
    if os.path.isfile('iFileList'): 
     print "file found" 
     self.train() 
     #self.classify() 

    #If file listing does not exist skip to train 
    if not os.path.isfile('iFileList'): 
     print "no file" 
     newfile = 'iFileList' 
     tempList = set() 
     subDir = './movie_reviews' 
     for filenames in os.listdir(subDir): 
      my_sub_path = os.path.join(os.sep,subDir,filenames) 
      tempList.add(filenames) 
      self.save("filenames", "try3") 
     f = [] 
     for fFileObj in os.walk("movie_reviews/"): 
      f.extend(fFileObj) 
      break 
     pickle.dump(f, open("save.p", "wb")) 
     self.save(f, "try4") 

     with open(newfile, 'wb') as fi: 
      pickle.dump(tempList, fi) 
      #print tempList 

     self.train() 
     #self.classify() 

def train(self):  
    '''Trains the Naive Bayes Sentiment Classifier.''' 
    print "File ready for training" 
    #Open iFileList to use as input for opening movie files 
    x = 0 
    OpenIFileList = open('iFileList','r') 
    print "iFileList now Open" 
    #Loop through the file 
    for line in OpenIFileList: 
     #print "Ready to read lines" 
     #print "reading line " + line 
     if x > 4: 
      if x % 2 == 0: 
       #print line 
       s = line 
       if '-' in s: 
        comp = s.split("'") 
        #print comp[2] 
        print comp[1] #This is What you need for t he movie file 
        compValue1 = comp[1] 
        #Determine Positive/Negative. 
        #compType is the variable I am storing it to. 
        compType = compValue1.split("-",2)[1] 
        #print compType #Prints that middle value like 5 or 1 
        # This will do the work based on the value. 
        if compType == '5': 
        # print "you have a five" #Confirms the loop I am in. 
         #If file does not exists create it 
         if not os.path.exists('PosList'): 
          print "no file" 
          file('PosList', 'w').close() 
         #Open file that needs to be reviewed for word count 
         compValue2 = "movie_reviews/" + compValue1 
         print compValue2 #Prints the directory and file path 
         OpenMovieList = open(compValue2,'r') 
         for commentLine in OpenMovieList: 
          commentPositive = commentLine.split(" ") 
          commentPositiveCounter = Counter(commentPositive) 
          #print commentPositiveCounter # " Comment Pos goes here" 
          #if commentLine != '' or commentLine != ' ': 
          #Get first word, second word, .... 
          if commentLine and (not commentLine.isspace()): 
           movieWordCount = self.tokenize(commentLine) 
           y = len(movieWordCount) #determines length of string 
           print y 
           z = 0 
           #print movieWordCount[0] # Shows the zero position in the file. 
           while z < y: 
            print "position " + str(z) + " word is " + movieWordCount[z] # Shows the word we are at and position id 

            with open("PosList") as OpenPos: 
             lines = OpenPos.readlines() 
             print lines 
             if movieWordCount[z] in lines: 
              print "found" 
             else: 
              print "not found" 
              lines.append(movieWordCount) 


            z = z + 1 

         #Close the files 
         OpenMovieList.close() 
         OpenPos.close() 


     x += 1 
     #for line2 in OpenIFileList.readlines(): 
     #for line in open('myfile','r').readlines(): 
      #do_something(line) 

    #Save results 
    #Close the File List 
    OpenIFileList.close() 



def loadFile(self, sFilename): 
    '''Given a file name, return the contents of the file as a string.''' 

    f = open(sFilename, "r") 
    sTxt = f.read() 
    f.close() 
    return sTxt 

def save(self, dObj, sFilename): 
    '''Given an object and a file name, write the object to the file using pickle.''' 

    f = open(sFilename, "w") 
    p = pickle.Pickler(f) 
    p.dump(dObj) 
    f.close() 

def load(self, sFilename): 
    '''Given a file name, load and return the object stored in the file.''' 

    f = open(sFilename, "r") 
    u = pickle.Unpickler(f) 
    dObj = u.load() 
    f.close() 
    return dObj 

def tokenize(self, sText): 
    '''Given a string of text sText, returns a list of the individual tokens that 
    occur in that string (in order).''' 

    lTokens = [] 
    sToken = "" 
    for c in sText: 
     if re.match("[a-zA-Z0-9]", str(c)) != None or c == "\'" or c == "_" or c == '-': 
      sToken += c 
     else: 
      if sToken != "": 
       lTokens.append(sToken) 
       sToken = "" 
      if c.strip() != "": 
       lTokens.append(str(c.strip())) 

    if sToken != "": 
     lTokens.append(sToken) 

    return lTokens 

答えて

0

書き込み用のファイルを開くには、

with open('PosList', 'w') as Open_Pos 
を使用することができます

withフォームを使用しているので、ファイルを閉じる必要はありません。 Pythonはwith-blockの終わりにそれを行います。

with open("PosList") as OpenPos: 
    lines = OpenPos.readlines() 
    print lines 
    if movieWordCount[z] in lines: 
     print "found" 
    else: 
     print "not found" 
     lines.append(movieWordCount) 
with open("PosList", "w") as OpenPos: 
    OpenPos.write(lines) 
+0

私はあなたが私を取っていると思います。だから、あなたがライン変数にデータを追加する方法が正しいか、あなたは余分コードOpenMovieList.close()OpenPos.close()を削除し、あなたのコードに2行を追加することができると仮定し

正しいトラックが、まだ動作していません。以前のコードで提供していたことに間違いがありました。主にオープンなものと:OpenPosとして( "POSLIST")オープンと :movieWordCount場合行に[Z] : 線= OpenPos.readlines() 印刷ライン I = 0 iが(ライン)でlen <ながら:他 –

+0

"が見つかり" プリント: 印刷 "が見つかりません" lines.append(movieWordCount [Z] + '1' + "\ n") 印刷ラインオープン( "POSLIST" と I + = 1 、 "w")Open_Posとして: Open_Pos.write(lines) –

+0

それはちょうど同じものを通して私をループしているようです無限の言葉。私はそれが想定されているようなファイル間をジャンプするのを見ていますが、見ている単語をインクリメントしていないし、配列された文をダンプする必要があるときにsamという単語 –

関連する問題