如何在txt文件中搜索。显示包含指定表达式的行及其后的行?

How to search in a txt file. Show the line that contains the specified expression and the line after that?

我有一个 .txt 文件,其中的行如下所示:

175- HAMURABI WAS THE CREATOR OF WHAT EMPIRE?
R: BABYLONIC
176- WAR OF 30 YEARS OCCURRED IN WHAT PERIOD?
R: 1618-1648
177- WHO IS THE VILLAIN OF THE CARTOON "THE SMURFS"?
R: GARGAMEL
178- TRUE NAME OF ERIC ARTHUR BLAIR?
R: GEORGE ORWELL
179- IN WHICH AFRICAN COUNTRY IS MOUNT KILIMANJARO LOCATED, WITH 5895 ALTITUDE METERS?
R: T ANZANIA

我希望代码显示(例如)带有 war of 30 years occurred in what period? 的行。它应该进行不区分大小写的搜索。

我真正想要的是这样的结果:

**176- WAR OF 30 YEARS OCCURRED IN WHAT PERIOD?
R: 1618-1648**

我知道如何打开文件和阅读行,但之后我就卡住了。如何搜索文件?

您可以打开文件并阅读所有行:

file = open("Path",mode="rt")
LineList = file.readlines()

LineList 现在是每行一个字符串值的列表。 您可以访问每一行及其索引(从 0 => Line 1 = Index 0 开始)

您可以使用 for 循环搜索列表并将每个字符串与搜索键进行比较。

searchKey = '176- WAR OF 30 YEARS OCCURRED IN WHAT PERIOD?'

def findIndex(searchKey):
    index = -1
    for line in LineList:
        index = index + 1
        linePosition = line.find(searchKey)
        if linePosition != -1:
            break
    return index

答案就是匹配行的索引 + 1

print(LineList[findIndex(Searchkey)])
print(LineList[findIndex(Searchkey) + 1])

Searchkey 将是您正在搜索的字符串

file = open("a.txt")
data = file.readlines();
file.close()
search_data = {data[i]:data[i+1] for i in range(len(data)-1)}

这应该会根据您的问题给出您的答案。如果你想匹配字典键上的模式你可以尝试匹配然后从字典中获取

这段代码解决了部分问题:

ques = []
substr = "my SearchedKey".lower()
with open ('pr.txt', 'rt', encoding="utf-8") as myfile:
    for line in myfile:
        if line.lower().find(substr) != -1:
            ques.append(line.rstrip('\n'))
for answ in ques:
    print(answ)

从那里开始,如何打印后面的行?

为我工作的那个:

a = "search"
lines = 0
resuls = []
resp = []
with open ("pr.txt", 'r', encoding="utf-8") as file:
    for l in file:
        lines += 1

        resp.append(l.rstrip())

        if a.lower() in l.lower():
            result.append((lines, l.rstrip()))

for i in resul:
    print(i[1])
    print(resp[i[0]])

非常感谢大家的帮助