代码之家  ›  专栏  ›  技术社区  ›  skysthelimit91

我的python输出缺少1个单词,我不确定原因(从文件中读取)

  •  0
  • skysthelimit91  · 技术社区  · 4 年前

    我的产出缺少最后一个词“千年”。我不知道为什么。

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

    区块报价

    input1.txt
    ammoniated
    millennium
    

    input1.txt的内容为:

    aspiration
    classified
    federation
    graduation
    millennium
    philosophy
    quadratics
    transcript
    wilderness
    zoologists
    

    输出为:

    aspiration
    classified
    federation
    graduation
    millennium
    

    注意事项:

    输出的末尾有一条换行符。所有输入文件 托管在zyLab中,文件名可以直接引用。 input1.txt可供下载,以便文件的内容 可以看到。在测试中,输入的第一个单词总是出现 在第二个单词输入之前按字母顺序排列。

    我的代码:

    fileName = input()
    lowerLimit = input()
    upperLimit = input()
    with open(fileName) as fileData:
        lst = fileData.readlines()
    
     
        
    for index, value in enumerate(lst):
        if value >= lowerLimit and value <= upperLimit:
            print(value.rstrip())
    

    此处显示的程序输出:

    aspiration
    classified
    federation
    graduation
    
    0 回复  |  直到 4 年前
        1
  •  0
  •   Vae Jiang    4 年前

    回答你的问题,我想可能是因为你 upperLimit 应该是 upperLimit + 1 自从 the end index for the list is exclusive.

    此外,将代码放入一个类中以实现可重用性可能是个好主意。

    以下是我将如何编写这个小项目(对于我的版本,你需要输入两个txt目录,但当输入文件名提取时,你总是可以改为读取单词列表txt)。

    class WordsFilter:
        def __init__(self, index_txt_dir: str, allWords_txt_dir: str):
            '''
            :param index_txt_dir: the txt file contains a file name, lower bound word, and upper bound word
            :param allWords_txt_dir: the txt file contains all words
            '''
            self._index_txt_dir = rf'{index_txt_dir}'
            self._allWords_txt_dir = rf'{allWords_txt_dir}'
    
        def _helper_read_file(self):
            '''
            :purpose: this function is used to read both txt files
            '''
            with open(self._index_txt_dir, 'r') as file:
                self.file_name, self.lower_bound, self.upper_bound = [x.strip() for x in file.readlines()]
    
            with open(self._allWords_txt_dir, 'r') as file:
                self.words_list = [x.strip() for x in file.readlines()]
    
        def _helper_cleaned_raw_output_index(self):
            '''
            : purpose: this function is used to handle the following situations
                1: lower bound words can be found, but an upper bound cannot find.
                    solutions: return all words starting from the lower bound (inclusive)
                2: the lower bound word comes after a higher bound word in the words list.
                    solutions: return switch lower index and upper index to return everything in between.
                3: both lower bound and upper bound word cannot be found.
                    solutions: return all words in words list read
            '''
            lower_index, upper_index = self._helper_raw_output_index()
    
            if lower_index > upper_index:
            # lower bound word can be found, but upper bound cannot find. ie: raw index as (4,0)
            # Solution: return all words starting from the lower bound (inclusive)
                if upper_index == 0:
                    return (lower_index, None)
                # lower bound word comes after higher bound word in the words list. ie: raw index as (4,3)
                # Solution: return switch lower index and upper index to return everything in between.
                else:
                    return (upper_index, lower_index + 1)
            # both lower bound and upper bound word cannot be found. ie: raw index as (0, 0)
            # Solution: return all words in words list read
            elif lower_index == upper_index:
                return (None, None)
            else:
                return (lower_index, upper_index + 1)
    
        def get_filtered_words(self):
            '''
            :purpose: This is the function you will call directly
            :return: filtered words list
            '''
            self._helper_read_file()
            low, upper = self._helper_cleaned_raw_output_index()
            return self.words_list[low:upper]
    
        def _helper_raw_output_index(self):
            '''
            :purpose: this function is used to get the raw index for lower and upper bound words. If any of them can found, it will be set as 0
            '''
            lower_index, upper_index = [0, 0]
            try:
                lower_index = self.words_list.index(self.lower_bound)
            except ValueError:
                print('Lower Bound Not In Words List')
            finally:
                try:
                    upper_index = self.words_list.index(self.upper_bound)
                except ValueError:
                    print('Upper Bound Not In Words List')
            return lower_index, upper_index
    
    words = WordsFilter(index_txt_dir= r'/index.txt', allWords_txt_dir= r'/input.txt')
    
    words.get_filtered_words()
    

    我希望这会有所帮助。

        2
  •  0
  •   SIGHUP    4 年前

    这个答案只使用readlines(),因为问题需要它。文件对象可以迭代,所以在这种情况下,readlines)并不是真正必要的。

    filename = input('Filename: ') # always nice to have a literal prompt
    lowerLimit = input('Lower limit: ')
    upperLimit = input('Upper limit: ')
    
    with open(filename) as fileData:
        for line in map(str.rstrip, fileData.readlines()):
            if line >= lowerLimit and line <= upperLimit:
                print(line)