【问题标题】:How do I print words in a specific alphabetical range coming from lines in a file?如何打印来自文件行的特定字母范围内的单词?
【发布时间】:2020-05-26 22:17:54
【问题描述】:

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

文本文件(input1.txt)包含:

aspiration
classified
federation
graduation
millennium
philosophy
quadratics
transcript
wilderness
zoologists

例如,如果我输入:

input1.txt
ammoniated
millennium

输出应该是:

aspiration
classified
federation
graduation
millennium

到目前为止,我尝试过:

# prompt user to enter input1.txt as filepath
filepath = input()
start = input()
end = input()
apending = False
out = ""

with open(filepath) as fp:
    line = fp.readline()
    while line:
        txt = line.strip()
        if(txt == end):
            apending = False
# how do I make it terminate after end is printed?? 
        if(apending):
            out+=txt + '\n'
        if(txt == start):
            apending = True               
        line = fp.readline()
    print(out)

但是,它似乎没有输出任何东西。非常感谢任何帮助调试或修复我的代码~

【问题讨论】:

    标签: python


    【解决方案1】:

    代码如下:

    # prompt user to enter input1.txt as filepath
    filepath = input()
    start = input()
    end = input()
    # apending = False
    # out = ""
    
    with open(filepath) as fp:
        while True:
            line = fp.readline()
            if not line:
                break
            txt = line.strip()
            if txt >= start and txt <= end:
                print(txt)
            if txt > end:
                break
    

    【讨论】:

      【解决方案2】:

      输入中没有一个字符串等于ammoniated,因此txt == start永远不会为真,因此apending永远不会设置为True,因此out += txt + '\n'永远不会执行,因此print(out)会打印最后是一个空字符串。

      您应该使用&lt;&gt; 将输入中的字符串与startend 进行比较。它们不应该是完全匹配的。

      【讨论】:

        【解决方案3】:

        这可以通过使用&lt;=&gt;= 运算符比较字符串,然后过滤匹配上下限条件的单词来完成。

        正如this article 中所说,“Python 字符串比较是使用两个字符串中的字符来执行的。两个字符串中的字符被一一比较。当找到不同的字符时,比较它们的 Unicode 值。具有较低的字符Unicode 值被认为更小。”

        f = open('input.txt')
        words = f.readlines()
        
        lower_bound = input('Set the lower bound for query')
        upper_bound = input('Set the upper bound for query')
        
        result = [word.strip() for word in words if lower_bound <= word.strip() <= upper_bound]
        print(result)
        
        f.close()
        
        

        print(result) 的输出,以及您提供的输入:

        ['aspiration', 'classified', 'federation', 'graduation', 'millennium']
        

        【讨论】:

          【解决方案4】:

          您可以使用关键字 break 退出 for 循环 例如

          for x in range(50):
              if x > 20:
                  break;
              else:
                  print(x);
          

          【讨论】:

            猜你喜欢
            • 2015-07-30
            • 2017-04-13
            • 2015-12-28
            • 2013-04-15
            • 1970-01-01
            • 1970-01-01
            • 2023-02-21
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多