2012-06-07 34 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