簡體   English   中英

如何在文本文件中搜索包含特定單詞的行,然后使用“找到”行創建一個新文件

[英]How to search a text file for lines that contain a specific word, then create a new file with the "found" lines

我需要在一些數據(文本文件)中搜索包含特定單詞的行,然后創建一個僅包含“找到”行的新文本文件。

例如,如果原始文本文件 (data.txt) 中的數據是:

Child 9  60lbs  Female Diabetes
Adult 25 180lbs Male   ADHD
Adult 46 200lbs Female epilepsy
Child 10 65lbs  Female ADHD

我要搜索關鍵字'Child',新的文本文件(output.txt)將是:

Child 9  60lbs  Female Diabetes
Child 10 65lbs  Female ADHD  

到目前為止,這是我的代碼,我真的不知道如何將找到的行寫入新文件。

def main():
    
    Word1 = 'Child'
    
    #open an existing file. 
    OriginalData = open('recordData.txt', 'r')
    datalist = []

    for line in OriginalData.readlines():
            if Word1 in line: 
                #write the line to new file.
    
if __name__=="__main__":
    main()
search_word = 'your search word here'
with open('data.txt') as file:  # opens it, then closes it automatically at the end of the with block
    lines = [line for line in file.read().split('\n') if search_word in line]

with open('output.txt', 'w+') as output_file:  # 'w+' specifies it can be written to and created
    output_file.write('\n'.join(lines))

現在我們可以分解lines = [line for line in file.read().split('\n') if search_word in line]

file.read()返回整個文件的字符串

.split('\n')將字符串轉換為列表,在每個換行符處打破它( '\n'是換行符)

if search_word in line所以它只添加帶有單詞的行

'\n'.join(lines)將選定的行重新組合在一起,然后使用write將其寫入文件

暫無
暫無

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

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