楼主: ReneeBK
3425 7

[书籍介绍] Introduction to Python for SPSS [推广有奖]

  • 1关注
  • 62粉丝

VIP

已卖:4897份资源

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49635 个
通用积分
55.6937
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57805 点
帖子
4005
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

楼主
ReneeBK 发表于 2014-6-12 04:40:55 |AI写论文

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币
Introduction to Python for SPSSIntroducing Python 1 – What and why
Introducing Python 2 – How It Basically Works
Introducing Python 3 – How To Use It
Introducing Python 4 – Installing and Testing
Introducing Python 5 – Five Essential Basics
Introducing Python 6 – Four Tips

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:introduction troduction python intro SPSS

已有 1 人评分经验 收起 理由
狂热的爱好者 + 60 精彩帖子

总评分: 经验 + 60   查看全部评分

本帖被以下文库推荐

沙发
ReneeBK 发表于 2014-6-12 04:44:38

藤椅
ReneeBK 发表于 2014-6-12 04:45:18

板凳
ReneeBK 发表于 2014-6-12 05:23:34

How can I write a Python program to rename variables in SPSS?


http://www.ats.ucla.edu/stat/spss/faq/renaming_vars_Python.htm

报纸
ReneeBK 发表于 2014-6-12 05:29:36
* Command to be executed depends on the existence of a given variable.
* Format is "varname ; command if varname exists; command if it does not exist"
* Raynald Levesque  www.spsstools.net  2005/10/11.

GET FILE='c:\program files\spss\employee data.sav'.
COMPUTE VarA = 3 .

HOST COMMAND=['ECHO VarA; COMPUTE VarA=2*VarA .; COMPUTE VarA=1.> c:\temp\varExists.txt'].

* The above HOST COMMAND creates a text file to pass parameters to the python script.
* Parameters are delimited by ";" Each command must end with a ".".
* The above varExists.txt file means that
*  if VarA exists, the command in the 2nd parameter "COMPUTE VarA=2*VarA." will be executed.
*  if VarA does NOT exist, the command in the 3rd parameter "COMPUTE VarA=1" will be executed.
* Macro calls or INSERT FILE commands could also be used instead of the simple commands used above.

*------------------------------.
BEGIN PROGRAM python.
import spss, win32api

try:
        f = open(r'c:\temp\varExists.txt','r')
        s = f.readline()
        f.close()
        win32api.DeleteFile(r'c:\temp\varExists.txt')
except:
        print "\n ***Error by Python script"       

if f and s:       
        vec = s.split(";")
        varExists = 0
        for i in range( spss.GetVariableCount() ):
                varName = spss.GetVariableName(i)
                if varName.upper() == vec[0].upper():
                        varExists = 1
                        print "\n*** variable exists"       
                        break
        if varExists == 0 and vec[2].strip() <> "":
                spss.Submit(vec[2])
                print "\n*** variable did NOT exist"
        elif varExists == 1 and vec[1].strip <> "":
                spss.Submit(vec[1])
END PROGRAM.
*------------------------------.

EXECUTE.

**************************************************************************************.
* Short command version (that is a version that is easy to use on a DAILY BASIS).
* the above python program is saved in "c:\temp\varExists.sps".

* Include the following macro in the macro.sps file.
*////////////////////////////.
DEFINE !VarExists(!POS=!CMDEND)
HOST COMMAND=[!QUOTE(!CONCAT('ECHO ',!UNQUOTE(!1), !UNQUOTE('> c:\temp\varExists.txt')))].
INSERT FILE="c:\temp\varExists.sps".
!ENDDEFINE.
*////////////////////////////.

* Example 1: variable exists.

GET FILE='c:\program files\spss\employee data.sav'.
COMPUTE VarA=2.
!VarExists "VarA; FREQ VAR=VarA .; COMPUTE VarA=1.".
EXECUTE.

* Example 2: when variable does not exist.

GET FILE='c:\program files\spss\employee data.sav'.
!VarExists "VarA; FREQ VAR=VarA .; COMPUTE VarA=1.".
EXECUTE.

* Example 3: multiline commands.
* Use macros to define what needs to be done in each case.

DEFINE !whenExist()
COMPUTE VarA = VarA * 2.
FREQ VAR = VarA
!ENDDEFINE.

DEFINE !whenNotExist()
COMPUTE VarA = 3.
TITLE "varA did not exist".
!ENDDEFINE.

GET FILE='c:\program files\spss\employee data.sav'.
!VarExists "VarA; !whenExist .; !whenNotExist.".
EXECUTE.

地板
ReneeBK 发表于 2014-6-12 05:30:10
* pass an argument to python.

**************** One method: using label of a variable ********************.

* To pass an argument to Python, define variable PythonArg and

GET FILE='c:\program files\spss\employee data.sav'.
NUMERIC PythonArg.
VARIABLE LABEL PythonArg "127; var1".

BEGIN PROGRAM python.
import spss
lastVar = spss.GetVariableCount() - 1
if spss.GetVariableName(lastVar) == "PythonArg":
        argument = "\n***Python received the following argument: " + spss.GetVariableLabel(lastVar)
else:
        argument = "\n***No arguments passed to Python"
print argument
END PROGRAM.

EXECUTE.
DELETE VAR PythonArg.


**************** Alternative method: using a text file  ********************.

* Note: This method is MORE promissing.

GET FILE='c:\program files\spss\employee data.sav'.
HOST COMMAND=['ECHO 127; var1 > c:\temp\PythonArg.txt'].

BEGIN PROGRAM python.
import spss, win32api

try:
        f = open(r'c:\temp\PythonArg.txt')
        arguments = f.readline()
        f.close()
        win32api.DeleteFile(r'c:\temp\PythonArg.txt')
        print "\n *** Python received the following arguments: " + arguments
except:
        print "\n***No arguments passed to Python"
print argument
END PROGRAM.

EXECUTE.

7
ReneeBK 发表于 2014-6-12 05:31:15

# Reference Hetland p. 427 (Beginning Python From Novice to Professional)
# Other resource: Chap 24 of Python in a Nutshel (Alex Martelli)
# Raynald Levesque August 2008

from xml.sax.handler import ContentHandler
from xml.sax import parse
import spss

# Change next line to match your requirements
fpath=r'C:/Test2'
fname=r'sample.xml'     # the enclosed sample data file


xmlFile  = r'%(fpath)s/%(fname)s' % vars()

class DataHandler(ContentHandler):
    """ Creates tab separated data files """

    in_extract = False

    def __init__(self, extract, wantList):
        ContentHandler.__init__(self)
        self.extract = extract
        self.data = []
        self.wantList = wantList
        # next 2 strings were copy/pasted from the XML document then 'cleaned'
        self.action_logAtt = 'id team1 team1_name team2 team2_name league league_id \
            date matchday season season_code start1 start2'.split()
        self.actionAtt = 'aid action_code activitytype result id minute second \
            field_position receiver team_id x y z pace last_modified'.split()
        self.DeletedactionAtt = self.actionAtt
        # next string was found inspection of XML file
        self.actionOpt ='subtype c1 c2 c3'.split()
        self.first_Action = True
        self.first_Log = True

    def startElement(self, name, attrs):
        self.in_extract = name in self.wantList
        #print name, attrs.keys()
        if self.in_extract:
            if name== 'action_log':
                self.data=["1\t"]                           #record type 1
                self.data.extend(["%s\t" % attrs.getValue(att) for att in self.action_logAtt])
                self.action_logID=attrs.getValue('id')      # will be added at beg of each child record

            elif name == 'action':
                self.data=["2\t", self.action_logID + '\t'] #record type 2
                self.dataOpt=['\t']*len(self.actionOpt)
                for idx,attrib in enumerate(self.actionOpt):
                    if attrs.has_key(attrib):
                        self.dataOpt[idx] = attrs.getValue(attrib) + '\t'
                self.data.extend(["%s\t" % attrs.getValue(att) for att in self.actionAtt])
                self.data.extend(self.dataOpt )

            elif name == 'Deletedaction':
                self.data=["3\t", self.action_logID + '\t'] #record type 3
                self.data.extend(["%s\t" % attrs.getValue(att) for att in self.DeletedactionAtt])

            # Insert var names in tab delimited file
            if self.first_Log:
                # extract[0] will contain both var names and attributes of 1st XML element
                vnames=['recType']
                vnames.extend(self.action_logAtt)
                vnames=["%s\t" % v for v in vnames]
                vnames.append('\n')
                vnames.extend(self.data)
                self.data=vnames
                self.first_Log = False
                # extract[1] will contain both var names and attributes of 2nd XML element
            elif self.first_Action and name in ['action','Deletedaction']:
                vnames=['recType','logID']
                vnames.extend(self.actionAtt)
                vnames.extend(self.actionOpt)
                vnames=["%s\t" % v for v in vnames]
                vnames.append('\n')
                vnames.extend(self.data)       # this is an in-place modif
                self.data = vnames
                self.first_Action = False      # we won't come back through this if

            text = ''.join(self.data) + '\n'
            self.extract.append(text)

    def endElement(self,name):
        if name in self.wantList:
            self.data = []
            self.in_extract = False

    def characters(self,string):
        if self.in_extract:
            self.data.append(string)


# Use the class to create the tab separated data file
# Note: If we were dealing with a very large file, it would be preferable to create
# the 2 text files within the DataHandler class

extract = []
wantList=['action_log','action','Deletedaction']        # Elements to extract
parse(xmlFile, DataHandler(extract, wantList))          # extract now contain the data
nameroot = fname[:fname.find('.')]                      #sample.xml --> sample
fLogName = r'%(fpath)s/%(nameroot)sLog' % vars()        # --> path/sampleLog
fActionName = r'%(fpath)s/%(nameroot)sAction' % vars()  #--> path/sampleAction
fLog = open(fLogName,'w')                   #File to contain action_log info
fAction = open(fActionName,'w')
try:
    for (i,s) in enumerate(extract):
        if len(s)> 0:
            s2 = s.encode('iso8859-1')      #unicode must be encoded before writing
            if s[0] in ['2','3'] or i==1:   #2nd line contains vnames of action
                fAction.write(s2)
            elif s[0] == '1' or i == 0:     #1st line contains vnames of log
                fLog.write(s2)
finally:
    fAction.close()
    fLog.close()

# The 2 tab delimited text files were then read using SPSS and the syntax was
# pasted below

cmd=r"""
    SET PRINTBACK=YES /MPRINT=YES.
    DATASET CLOSE ALL.
    GET DATA  /TYPE = TXT
     /FILE = "%(fLogName)s.txt"
     /DELCASE = LINE
     /DELIMITERS = "\t"
     /ARRANGEMENT = DELIMITED
     /FIRSTCASE = 2
     /IMPORTCASE = ALL
     /VARIABLES =
     recType F1.0
     id F6.0
     team1 F3.0
     team1_name A19
     team2 F3.0
     team2_name A16
     league A14
     league_id F1.0
     date A22
     matchday F2.0
     season A9
     season_code F2.0
     start1 A22
     start2 A22.
    CACHE.
    SAVE OUTFILE= "%(fLogName)s.sav".

    GET DATA  /TYPE = TXT
     /FILE = "%(fActionName)s.txt"
     /DELCASE = LINE
     /DELIMITERS = "\t"
     /ARRANGEMENT = DELIMITED
     /FIRSTCASE = 2
     /IMPORTCASE = ALL
     /VARIABLES =
     recType F1.0
     logID F6.0
     aid F7.0
     action_code A4
     activitytype F2.0
     result F1.0
     id F2.0
     minute F2.0
     second F2.0
     field_position F2.0
     receiver F5.0
     team_id F3.0
     x F5.3
     y F5.3
     z F5.3
     pace F5.3
     last_modified A22
     subtype F2.0
     c1 F1.0
     c2 F1.0
     c3 F1.0 .
    CACHE.
    SAVE OUTFILE="%(fActionName)s.sav".
""" % vars()

spss.Submit(cmd)

8
ReneeBK 发表于 2014-6-12 05:36:18
* Run macro only if there are cases.
* Raynald Levesque 2005/11/13  www.spsstools.net .

***************************.
*Step 1 (one time only):
***************************.

* Save next program block as "c:\temp\Run local if there are cases.SPS".
*---------------------------------.
BEGIN PROGRAM.
import spss
if spss.GetCaseCount() == 0:        # cannot run !local, print message & exit.
        spss.Submit("TITLE *File is empty, will not run the local macro")
else:
        spss.Submit("!local.")        # instruct SPSS to run !local
END PROGRAM.

*The above is called a "program block".

***************************.
* Step2 (one time only):
***************************.

* Add the following to the macro file .
DEFINE !RunIfCase().
INSERT FILE="c:\temp\Run local if there are cases.SPS".
!ENDDEFINE.

*Note: Program blocks cannot be contained within a macro definition
* but the above is acceptable.


*Suppose initial syntax is
GET FILE="C:\Program Files\SPSS\employee data.sav".
SELECT IF jobcat=10.
GRAPH /BAR(SIMPLE)=COUNT BY jobcat .
FREQ VAR= gender.

* EXAMPLE #1.

*Modify syntax as follows.

GET FILE="C:\Program Files\SPSS\employee data.sav".
SELECT IF jobcat=3.
EXECUTE.
/* the above EXE is necessary to update the number of cases */
DEFINE !local()
GRAPH /BAR(SIMPLE)=COUNT BY educ .
FREQ VAR= gender.
!ENDDEFINE .
!RunIfCase.


* EXAMPLE #2.

GET FILE='C:\Program Files\SPSS\employee data.sav'.
SET MPRINT=NO.
SELECT IF 1=0 /* To have an empty dataset and show that the macro works as expected */ .
EXE.

*Next macro contains the code to be executed when the active dataset is not empty.
DEFINE !local()
SET MPRINT=YES.
GRAPH /BAR(SIMPLE)=COUNT BY educ .
!ENDDEFINE.

!RunIfCase.

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加好友,备注cda
拉您进交流群
GMT+8, 2025-12-24 08:59