[英]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.