回答你的问题,我想可能是因为你
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()
我希望这会有所帮助。