2015-09-06 32 views
-7

所以我們的目標是創建一個布爾(true和false)表達式求值器。我採取的方式是從我正在使用的書中獲得所有真實的表達,並將它們放入列表中。然後從輸入文件我只是採取了第一行,並使用「如果在字符串中的行:」給我,如果輸入完全匹配列表中的一個字符串。但我想讓它讀取文本文件的每一行,並告訴我每行是真還是假,並且不知道如何使其工作,我知道它是讀第一行並告訴我它是真/假,假,但我不知道如何做多行。如何讀取輸入文本文件中的每一行並確定每行是真還是假?

這裏是我到目前爲止的代碼:

input_file = open('input.txt', 'r') 
output_file = open('output.txt', 'w') 
#List expressions that are true 
strings = ['T', '(~ F)','T & T', 'T | T', 'T | F', 'F | T', '~ (T & F)', 
     '~ (F & T)', '~ (F & F)', '(T | F) & ~ (T & F)' , '(F | T) & ~ (F & T)', 
     '(T & T) | (~ T)', '(T & T) | (~ F)', '(T & F) | (~ F)', '(F & T) | (~ F)', 
     '(F & F) | (~ F)', '~ (~ T)', '(~ F) & (~ F)', '(~ T) | (~ F)', '(~ F) | (~ T)', 
     '(~ F) | (~ F)', 'T | (~ T)'] 
#read input// only use the first line// if line == strings then return true if not return false 
lines = input_file.readline() 
lines = input_file.readline() 


def readline(line): 
    if lines in strings: 
        return True 
    else: 
        return False 

if readline(lines) == True: 
    output_file.write('True') 
    print('Check output.txt.') 
else: 
    output_file.write('False') 
##       'The expression in BooleanExpression.txt is FALSE or the following:\n' 
##       'You typed it in wrong, or expression was not  defined in the\n' 
##       '"Discrete Mathematics with Applications" book.') 
    print('Check output.txt.') 
#close files   

input_file.close() 
output_file.close() 

所以,如果我的input.txt中看起來是這樣的:

(~ F) 
(~ T) 
T | T 

此output.txt應該是這樣的:

True 
False 
True 
+0

您可以將代碼粘貼到此處而不是pastebin,它足夠簡短並且可讀性更好。 –

+0

尋求調試幫助的問題(**「爲什麼這個代碼不工作?」**)必須包含所需的行爲,*特定的問題或錯誤*和*在問題本身中重現它所需的最短代碼* **。沒有**明確問題陳述**的問題對其他讀者沒有用處。請參閱:[如何創建最小,完整和可驗證示例](http://stackoverflow.com/help/mcve)。請***請勿***將您的代碼發佈到外部網站上。 – MattDMo

+0

請問您可以發佈您的代碼,以及您在問題本身中嘗試過的內容。謝謝。 –

回答

0

既然idk如何在評論中對事物進行格式化,如果這是一件事情,那麼我現在擁有的東西。 @achampion

def readline(lines): 
    if lines in strings: 
     return True 
    else: 
     return False 

with open('output.txt', 'w+') as output_file: 
    with open('input.txt', 'r') as input_file: 
     for lines in input_file: 
      if readline(lines) == True: 
       output_file.write('True\n') 
       print('true') 
      else: 
       output_file.write('False\n') 
       print('false') 
+0

它看起來沒問題,我已經更新了一點,希望有幫助。 – AChampion

+0

對此有點遲了,但唯一的問題來自我使用的字符串,而不是一切正常。在文本文件中,您將使用enter來創建一個我沒有考慮到的新行。所以我在\ n之後重複了\ n的字符串。 – jesseym

2

您需要將readline放入循環中。然而文件類型的對象支持迭代,所以你可以只使用:

with open('input.txt', 'r') as input_file: 
    for line in input_file: 
     if readline(line) == True: 
      ... 

然而,你可能要考慮實際解析文本進行評價,這樣可以解決任何布爾表達式。

+0

因此,它使用您編寫的示例代碼進行循環,但當執行多於1行時它會產生錯誤。我測試了一條線,它給了我正確的答案,但是當我使用超過1的時候,它給所有的東西都是錯誤的。如果任何事情看起來不正確,我會繼續忽略更多的想法嗎? – jesseym

+0

@ jesseym沒有看到你的代碼很難說出什麼問題 – AChampion

+0

發佈它作爲一個答案,因爲我是新發布和idk如何格式化的東西在評論中。 – jesseym

相關問題