从单独的文件中读取答案

时间:2014-07-13 12:11:08

标签: python python-2.7 python-idle python-import

我坚持使用此代码。 所以,我正在制作一个回答人们问题的IRC机器人。当提出问题时,我将其写入.txt文件;

Main.py

Import os
Import hi
Question_file = 'question.txt'
Answer_file = 'answer.txt'

while True:

  Question = raw_input ("Question?").lower()

  with open(Question_file, "w") as q:
                   q.write(Question.lower())
                   q.close()

  with open(Answer_file, "r") as m:
    answer = m.read()

  if 'hi' in Question:
     print ("hi")

  else:
    print answer

现在一切都好。问题在于hi.py

Hi.py

Import os
Import string
Question_file = 'question.txt'
Answer_file = 'answer.txt'


with open (Question_file, "r") as f:
  question = f.read()

  if "what year is it" in question:
     with open(Answer_file, "w") as r:
       r.write("2014")
  if "what month is it" in question:
     with open(Answer_file, "w") as r:
       r.write("July")

问题是,Hi.Py不会写出正确答案吗?它只是写出第一个问题的答案,并在每次询问问题时打印答案?

1 个答案:

答案 0 :(得分:0)

当你这样做时

import hi

文件hi.py执行(一次),并且其对象可供导入程序的命名空间访问。

让我们看看hi.py做了什么:

with open (Question_file, "r") as f:   # Read entire file question.txt
  question = f.read()                  # into the variable "question"

  if "what year is it" in question:    # Look for this text;
     with open(Answer_file, "w") as r: # if found, *CREATE A NEW FILE* answers.txt
       r.write("2014")                 # and write "2014" to it.
  if "what month is it" in question:   # Same for the next text -
     with open(Answer_file, "w") as r: # if that's present, overwrite the file
       r.write("July")                 # with the text "July"

因此,您可能希望使用a代替w,因此其他字词不会覆盖之前的字词。我猜你应该在每个单词后面写一些分隔符(\n)。

现在让我们看一下main.py做了什么(之后执行hi.py并且没有做任何事情):

while True:
  Question = raw_input ("Question?").lower() # Get question from user

  with open(Question_file, "w") as q:        # Create a new file with the question
                   q.write(Question.lower()) # in lowercase
                   q.close()                 # no need for close() here!

  with open(Answer_file, "r") as m:          # Read the answer file
    answer = m.read()                        # regardless of what's in it

  if 'hi' in Question:
     print ("hi")                            # Python 3 syntax?

  else:
    print answer                             # Python 2 syntax?

这将持续到您点击Ctrl-C