簡體   English   中英

我正在努力從 python 的文本文件中讀取特定的單詞和行

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

我希望我的代碼能夠找到用戶要求的內容並打印以下 5 行。 例如,如果用戶在系統中輸入“james”,我希望它在文本文件中找到該名稱並讀取它下面的 5 行。 這甚至可能嗎? 我在瀏覽互聯網時發現的只是如何閱讀特定的行。

所以,你想讀一個.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()

現在,我們用 for 循環iterate (循環)該行,我們必須將“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變量仍然等於它最初設置的值,那么它顯然還沒有找到“詹姆斯”這個詞。

接下來,我們應該找到接下來的五行並將其保存到另一個變量中:

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='')

我希望我對您有所幫助。

好,當然。 假設您搜索的關鍵字(“james”)是keywrd ,而Xlines是您想要返回的匹配后的行數

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(),您將得到一個列表,您可以在閑暇時打印該列表。 我的回報如下:

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM