2012-06-07 44 views
1

pyparsing的作者Paul McGuire是kind enough to help a lot with a problem I'm trying to solve。我们在第一场比赛中打入了一球,但我甚至无法将球投进球门线。孔子说,如果他给了一个学生1/4的解决方案,并且他没有与其他3/4一起回来,那么他不会再教这个学生。所以这是经过近一个星期的沮丧和非常焦虑,我问这个...python&pyparsing newb:如何打开文件

如何打开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() 
+1

http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files – monkut

回答

2

看起来你需要一些帮助把它放在一起。 @BrenBarn的建议是独一无二的,在你把所有的东西放在一起之前,你需要解决简单复杂的问题。我可以通过给你一个你正在尝试做的最简单的例子来帮助你,用一个更简单的语法。您可以将其用作learn how to read/write a file in python的模板。考虑输入文本文件data.txt

cat 3 
dog 5 
foo 7 

让我们解析这个文件,并输出结果。有一些乐趣,让我们通过2 mulpitply第二栏:

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 is really just a simple shortcut around parseString, pretty much the equivalent of expr.parseString(open(filename).read()) .

+0

非常感谢你*随着睡眠时间的推移,这种策略今天早上终于在开车上班时深入我的脑海。我的文件将是“1”,然后我打开它,添加一个,并将其保存为输出。感谢您确认该策略,并展示了一个中间步骤。 – Niels

3

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

+0

感谢,是的,不管你信不信,我其实已经在一个标签中打开了。现在我已经在patientRecord 的第32行File“MyParser.py”中匹配partMatch.searchString(datafile.read()): AttributeError:'str'对象没有属性'read',这可能会更好,我真的不知道。感谢 – Niels

+0

我认为这可能与此有关:http://pyparsing.wikispaces.com/message/view/home/53509072 – Niels

+4

你应该尝试创建一个简单得多的程序,它只是读入一个文件并打印出来。然后创建一个程序读入一个简单的文件并在其上运行一个简单的pyparsing语法。逐渐增加程序的复杂性,直到它能够处理您的实际任务。如果你不熟悉Python,试着从编写程序开始,去做你想做的事是不明智的。人们实际上希望程序执行的大多数事情都很复杂。你需要开始简单。 – BrenBarn