0
열차 기능이 파이썬에서 올바르게 작동하도록하는 데 문제가 있습니다. 나는 def 함수를 수정할 수 없다. 나는 PosList에 대해 한 번에 하나씩 두 번째 파일을 읽어야하고 OpenPos에서 movieWordCount [z]의 값과 일치해야하는 시점에 있습니다. 파일이 있다면, 나는 t hat 줄 (공백으로 세분화 됨) 중 하나에 의해 2 열을 인식하는 것이 좋다. 그렇지 않으면 파일 끝에 파일을 추가해야합니다. 작동하지 않습니다. 값이 누락 된 경우 값을 추가하지 않으며 값이있는 경우 값을 찾을 수 있는지 확실하지 않습니다. 나는 이틀 동안 일하게되어 붙어 있었다. 여기 파일 열기 및 데이터 저장을위한 파이썬 코딩
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
올바른 트랙이지만 여전히 작동하지 않습니다. 내가 제공 한 초기 코드에서 실수를 발견했습니다. 주로 열린 물건 : ("PosList")를 연 OpenPos로서 : 라인 = OpenPos.readlines() 인쇄 라인 I = 0 난 (선) 렌 <동안 : 경우 movieWordCount [Z]에서 라인들 "발견" 인쇄 –
다른 : 인쇄 "없는" lines.append 인쇄 라인 ("PosList"열기와 I + = 1 (movieWordCount는 [Z] + "1"+ "\ n")를, "w") Open_Pos로 : Open_Pos.write (lines) –
그냥 같은 나를 통해 반복 것 같습니다 지금 끝없이 단어. 나는 그것이 파일들 사이에서 점프하는 것을 볼 수 있지만 그것이보고있는 단어를 증가시키지 않는다. 주기적으로 배열 된 문장을 덤핑해야 할 때 sam이라는 단어가 수천 번 덤프 된 후에 발견되지 않는다. –