【问题标题】:how do I output a list of strings that fall alphabetically between two input values如何输出在两个输入值之间按字母顺序排列的字符串列表
【发布时间】:2020-03-05 05:41:35
【问题描述】:

我收到了一个名为 input1.txt1 的文本文件,该文件包含以下内容

aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists

编写一个程序,首先读取输入文件的名称,然后是两个字符串,表示搜索范围的下限和上限。应该使用 file.readlines() 方法读取文件。输入文件包含一个按字母顺序排列的十个字母字符串列表,每个字符串位于单独的行中。您的程序应该从列表中输出该范围内(包括边界)的所有字符串。

前:

Enter the path and name of the input file: input1.txt
Enter the first word: ammunition
Enter the second word (it must come alphabetically after the first word): millennium
The words between ammunition and millennium are:
aspiration
classified
federation
graduation
millennium

【问题讨论】:

  • 到目前为止你尝试了什么?

标签: python


【解决方案1】:
file_to_open = input()
bound1 = input()
bound2 = input()

with open(file_to_open) as file_handle:
    list1 = [line.strip() for line in file_handle]

out = [x for x in list1 if x >= bound1 and x <= bound2]

out.sort()
print('\n'.join(map(str, out))) 

【讨论】:

    【解决方案2】:

    使用不等式的列表推导来检查字符串范围:

    out = [x for x in your_list if x >= 'ammunition' and x <= 'millennium']
    

    这假设您的范围在两端都包含,也就是说,您希望在范围的两端都包含ammunitionmillennium

    要进一步对out 列表进行排序,然后写入文件,请使用:

    out.sort()
    f = open('output.txt', 'w')
    text = '\n'.join(out)
    f.write(text)
    f.close()
    

    【讨论】:

    • @BoseongChoi 我不知道比较运算符可以在 Python 中链接 :) 谢谢。恕我直言,两者都有效,但同样具有可读性:)
    • 哦,我明白了,但是我如何将这些新值写回文件并像示例中所示那样显示输出?我必须创建一个新文件吗?我不能只打印出列表,因为列表中的每个单词都以 '\n' 结尾,所以每个单词都会跳到新行
    【解决方案3】:

    如果你应该使用 readline() 试试这个:

    filepath = 'Iliad.txt'
    start = 'sometxtstart'
    end = 'sometxtend'
    apending = False
    out = ""
    with open(filepath) as fp:
        line = fp.readline()
        while line:
            txt = line.strip()
            if(txt == end):
                apending = False
            if(apending):
                out+=txt + '\n'
            if(txt == start):
                apending = True               
            line = fp.readline()
    print(out)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2013-06-08
      相关资源
      最近更新 更多