蟒蛇& pyparsing newb:如何打开文件

时间:2012-06-07 05:59:43

标签: python pyparsing

pyparsing的作者Paul McGuire是kind enough to help a lot with a problem I'm trying to solve。我们在第一场比赛中以一个球场进球,但我甚至无法在球门线上踢球。孔子说,如果他给了学生1/4的解决方案,并且他没有和其他的3/4一起回来,那么他就不会再教那个学生了。所以经过近一周的挫折之后,我非常担心地问这个......

如何打开输入文件进行pyparsing并将输出打印到另一个文件?

这是我到目前为止所做的,但这完全是他所有的工作

from pyparsing import *
datafile = open( 'test.txt' )
# Backaus Nuer Form
num = Word(nums)
accessionDate = Combine(num + "/" + num + "/" + num)("accDate")
accessionNumber = Combine("S" + num + "-" + num)("accNum")
patMedicalRecordNum = Combine(num + "/" + num + "-" + num + "-" + num)("patientNum")
gleason = Group("GLEASON" + Optional("SCORE:") + num("left") + "+" + num("right") + "=" + num("total"))

patientData = Group(accessionDate + accessionNumber + patMedicalRecordNum)

partMatch = patientData("patientData") | gleason("gleason")

lastPatientData = None

# PARSE ACTIONS

def patientRecord( datafile ):
    for match in partMatch.searchString(datafile):
        if match.patientData:
            lastPatientData = match
        elif match.gleason:
            if lastPatientData is None:
                print "bad!"
                continue
            print "{0.accDate}: {0.accNum} {0.patientNum} Gleason({1.left}+{1.right}={1.total})".format(
                            lastPatientData.patientData, match.gleason
                            )

patientData.setParseAction(lastPatientData)

# MAIN PROGRAM

if __name__=="__main__":
    patientRecord()

2 个答案:

答案 0 :(得分:3)

看起来您需要调用datafile.read()才能读取文件的内容。现在你试图在文件对象本身上调用searchString,而不是文件中的文本。您应该仔细查看Python教程(特别是this section)以快速了解如何读取文件等。

答案 1 :(得分:2)

看起来你需要一些帮助把它放在一起。 @BrenBarn的建议是现场的,在你把它们放在一起之前处理简单复杂的问题。我可以通过一个简单的语法为你提供一个你想要做的最小例子。您可以将其用作learn how to read/write a file in python的模板。考虑输入文本文件data.txt

cat 3
dog 5
foo 7

让我们解析这个文件并输出结果。为了获得乐趣,让我们将第二列改为2:

from pyparsing import *

# Read the input data
filename = "data.txt"
FIN      = open(filename)
TEXT     = FIN.read()

# Define a simple grammar for the text, multiply the first col by 2
digits = Word(nums)
digits.setParseAction(lambda x:int(x[0]) * 2)

blocks   = Group(Word(alphas) + digits)
grammar  = OneOrMore(blocks)

# Parse the results
result = grammar.parseString( TEXT )
# This gives a list of lists
# [['cat', 6], ['dog', 10], ['foo', 14]]

# Open up a new file for the output
filename2 = "data2.txt"
FOUT = open(filename2,'w')

# Walk through the results and write to the file
for item in result:
    print item
    FOUT.write("%s %i\n" % (item[0],item[1]))
FOUT.close()

这在data2.txt中提供:

cat 6
dog 10
foo 14

打破每一块直到你明白它。从这里开始,您可以慢慢地将这个最小的例子适应上述更复杂的问题。从Paul himself notes开始读取文件(只要它相对较小)是可以的:

  

parseFile实际上只是围绕parseString的简单快捷方式   相当于expr.parseString(open(filename).read())