简体   繁体   中英

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

There is a paragraph I need to read and I neded to copy the line which only has the keyword.

Paragraph is something like this:

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 

My algorithm:

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

try this couple lines of code:

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

or one liner:

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

If you are trying to read the paragraph from a file:

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM