簡體   English   中英

Python:如何讀取段落的每一行並復制具有特定單詞的行

[英]Python : How to read every line of a paragraph and copy the line which has a specific word

有一段我需要閱讀,我需要復制只有關鍵字的行。

段落是這樣的:

aa
a
aaa
aaaaa
[new,aaa] < name of the file with path ] //asabbsjk
orem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap
[mod] <name of the file with path 

我的算法:

if keyword exists in the line :
      copy that line 
else: 
      leave it

試試這幾行代碼:

copy_lines= []
for line in paragraph.split('\n'):
    if keyword in line:
        copy_lines.append(line)
print(copy_lines)

或一個班輪:

copy_lines= [line for line in paragraph.split('\n') if keyword in line]

如果您嘗試從文件中讀取段落:

keyword = "your_keyword"

with open("demofile.txt", "r") as f:
    line_list = f.readlines()
    magic_lines = [line for line in line_list if keyword in line]

暫無
暫無

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

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