我正在努力从 python 中的文本文件中读取特定的单词和行

I am struggling with reading specific words and lines from a text file in python

我希望我的代码能够找到用户要求的内容并打印以下 5 行。例如,如果用户在系统中输入“james”,我希望它在文本文件中找到该名称并阅读它下面的 5 行。这可能吗?我在浏览互联网时所发现的只是如何阅读特定行。

是的,当然。假设您搜索的关键字(“james”)是 keywrd 并且 Xlines 是您想要 return

def readTextandSearch1(txtFile, keywrd, Xlines):

    with open(txtFile, 'r') as f:  #Note, txtFile is a full path & filename
        allLines = f.readlines()  #Send all the lines into a list
        #with automatically closes txt file at exit

    temp = []  #Dim it here so you've "something" to return in event of no match
    for iLine in range(0, len(allLines)):
        if keywrd in allLines[iLine]:
            #Found keyword in this line, want the next X lines for returning
            
            maxScan = min(len(allLines),Xlines+1)  #Use this to avoid trying to address beyond end of text file.
            for iiLine in range(1, maxScan):
                temp.append(allLines[iLine+iiLine]
            
            break #On assumption of only one entry of keywrd in the file, can break out of "for iLine" loop

    return temp

然后通过使用适当的参数调用 readTextandSearch1(),您将获得一个列表,您可以在闲暇时打印该列表。我将 return 如下:

rtn1 = readTextAndSearch1("C:\Docs\Test.txt", "Jimmy", 6)

if rtn1:  #This checks was Jimmy within Test.txt
    #Jimmy was in Test.txt
    print(rtn1)

所以,你想读一个 .txt 文件,你想读,比方说 James 这个词和它后面的 5 行。

我们的示例文本文件如下:

Hello, this is line one
The word James is on this line
Hopefully, this line will be found later,
and this line,
and so on...
are we at 5 lines yet?
ah, here we are, the 5th line away from the word James
Hopefully, this should not be found

让我们想想我们必须做什么。


我们必须做什么

  • 打开文本文件
  • 找到单词'James'所在的行
  • 找到接下来的 5 行
  • 将其保存到变量
  • 打印出来

解决方案

让我们把我们的文本文件命名为info.txt。你可以随便叫它。

首先,我们必须打开文件并将其保存到变量中:

file = open('info.txt', 'r') # The 'r' allows us to read it

然后,我们必须将其中的数据保存到另一个变量中,我们将以列表的形式进行:

file_data = file.readlines()

现在,我们 iterate(遍历)带有 for 循环的行,我们必须将 'James' 所在的行保存到另一个变量:

index = 'Not set yet'
for x in range(len(file_data)):
    if 'James' in file_data[x]:
        index = x
        break
    
if index == 'Not set yet':
    print('The word "James" is not in the text file.')

如您所见,它遍历列表,并检查单词 'James'。如果它找到它,它会打破循环。如果index变量还是和原来设置的一样,显然没有找到'James'.

这个词

接下来,我们应该找到接下来的五行,并将其保存到另一个变量中:

five_lines = [file_data[index]]
for x in range(5):
    try:
        five_lines.append(file_data[index + x + 1])
    except:
        print(f'There are not five full lines after the word James. {x + 1} have been recorded.')
        break

最后,我们将打印所有这些:

for i in five_lines:
    print(i, end='')

完成!

最终代码

file = open('info.txt', 'r') # The 'r' allows us to read it
file_data = file.readlines()


index = 'Not set yet'
for x in range(len(file_data)):
    if 'James' in file_data[x]:
        index = x
        break
    
if index == 'Not set yet':
    print('The word "James" is not in the text file.')


five_lines = [file_data[index]]
for x in range(5):
    try:
        five_lines.append(file_data[index + x + 1])
    except:
        print(f'There are not five full lines after the word James. {x + 1} have been recorded.')
        break
    
for i in five_lines:
    print(i, end='')

希望对您有所帮助。