循环用户输入到文本文件。怎么做?

时间:2015-11-28 23:38:05

标签: python-3.x

这一点是它要求输入(字/字母和数字),然后将输入保存到文本文件。由于它是一个循环,它应该保存所有" corret"输入到文件。我的问题是我在哪里放置最后3行还是我还需要更多东西?

var result = '{"entry":[ ';

function query(){
var results = getNumberResults();
if(results>0)
{
    var pages = Math.ceil(results/25);
    var i;
    for(i=0; i<pages; i++){
        $.when($.ajax({
          url: url,
          type: "GET",
          async: false,
          headers: {'Accept':'application/json'},
          success: function(data){
            $.each( data['search-results']['entry'], function( i, item ) {
                get info from json and save it in my variable

                if(data['search-results']['entry'][i]['citedby-count'] > 0)
                    getCitedBy(data['search-results']['entry'][i]['eid']);
                else{
                    result += '"children-id":[]},';
                }
            });
          }
        }));
    }
}
result = result.slice(0,-1);
result += "]}";
}

function getCitedBy(eid){
var results = getCitedByNumberResults(eid);
if(results>0)
{
    var pages = Math.ceil(results/25);
    var i;
    for(i=0; i<pages; i++){
        $.when($.ajax({
          url: url,
          type: "GET",
          async: false,
          headers: {'Accept':'application/json'},
          success: function(data){
            $.each( data['search-results']['entry'], function( i, item ) {
                get info from json and save it in my variable

                if(data['search-results']['entry'][i]['citedby-count'] > 0)
                    getCitedBy(data['search-results']['entry'][i]['eid']);
                else{
                    result += '"children-id":[]},';
                }
            });
          }
        }));
    }
}
}

function getNumberResults(){
var innerResult;
$.ajax({
  url: url,
  type: "GET",
  async: false,
  headers: {'Accept':'application/json'},
  success: function(output){
    innerResult = output['search-results']['opensearch:totalResults'];
  },
  error: function (xhr, ajaxOptions, thrownError) {
    innerResult = 0;
  }
});
return innerResult;
}

function getCitedByNumberResults(eid){
var innerResult;
$.ajax({
  url: url,
  type: "GET",
  async: false,
  headers: {'Accept':'application/json'},
  success: function(output){
    innerResult = output['search-results']['opensearch:totalResults'];
  },
  error: function (xhr, ajaxOptions, thrownError) {
    innerResult = 0;
  }
});
return innerResult;
}
def doit():                    # not important
    print("lalla")             # not important

def start():
    x = input("Write something (something)(nr)(C): ").split(' ')  # write a text and number. Using split to get two answers

    if 'C' in x:         # 'C' is for exit
        doit()
    else:
        try:              
            a = x[0]       # first string from input 
            b = x[1]         # second string from input 
            function(a,b)      # use them in next function
        except:
            start()             # if something goes wrong start again

def function(a,b):

    if not a.isalpha() or len(a) < 1:   # if a is not alpha or longer than 1
        start()                           # then back to input
    elif not b.isdigit() or int(b) < 1:    # if b is not number and bigger than 1
        start()    #then back to input
    else:
        print("Got it!")          # if everything is correct then says 'got it' and ask again till user inputs 'C'
        start()

start()

1 个答案:

答案 0 :(得分:0)

放线

f = open("database.txt", "w")  # open a text file for saving inputs

在全局调用开始之前(最后一行)。

您可以随时写入该文件。由于您没有存储输入数据,因此您可以放置​​&#34; write&#34;排在&#34;否则&#34;功能分支。

最后,&#34;关闭&#34;打电话并非真的有必要,并且无论如何都会在节目结束时完成。

但是,我建议您重构代码以使用while循环而不是递归,如下所示:

f = open("database.txt", "w")
while True:
    try:
        a, b = input("...").split(' ')
        f.write(str(a) + ' ' + str(b) + '\n')

    except:
        #stop looping when there aren't two things in the line
        break

f.close()