这是我需要的代码的完整示例 我已经使用示例文本文件编辑了完整的帖子 输入和输出
文字档案: -
Mohammed
Ahmed
Mansour
Sami
Sameer
Ukhlof
Asfar
Virus
Ameer
AbuAlameer
Ismail
Belal
Heba
Mama
Papa
示例输入: -
Enter a name : Ukhlof
Enter How much names you want to copy before that name : 10
输出:
From Up :-
Mohammed
Ahmed
Mansour
Sami
Sameer
Ukhlof
From Down :-
Belal
Heba
Mama
Papa
您的代码输出: -
From up:
Mohammed
Ahmed
Mansour
Sami
Sameer
From Down:
Papa
答案 0 :(得分:1)
import collections
def get(infilepath, name, n):
d = collections.deque(maxlen=n)
with open(infilepath) as infile:
line = infile.readline()
lines = 1
while line:
word = line.strip()
if word == name:
print("From up:")
for item in d:
print(item)
print(word)
break
d.append(word)
line = infile.readline()
lines += 1
print("From Down:")
if n-lines > 0:
n -= lines
d = collections.deque(maxlen=n)
while word:
d.append(word)
word = infile.readline().strip()
if not word:
break
for word in d:
print(word)
用法:
def main():
name = input("Enter a name: ")
n = int(input("How many lines? "))
infilepath = 'blah'
get(infilepath, name, n)
输入文件:
Mohammed
Ahmed
Mansour
Sami
Sameer
Ukhlof
Asfar
Virus
Ameer
AbuAlameer
Ismail
Belal
Heba
Mama
Papa
输出:
In [184]: main()
Enter a name: Ukhlof
How many lines? 10
From up:
Mohammed
Ahmed
Mansour
Sami
Sameer
Ukhlof
From Down:
Belal
Heba
Mama
Papa