为了账号安全,请及时绑定邮箱和手机立即绑定

Python:如何读取段落的每一行并复制具有特定单词的行

Python:如何读取段落的每一行并复制具有特定单词的行

跃然一笑 2023-12-29 15:32:44
我需要阅读一个段落,我需要复制只有关键字的行。段落是这样的:aaaaaaaaaaa[new,aaa] < name of the file with path ] //asabbsjkorem 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
查看完整描述

2 回答

?
宝慕林4294392

TA贡献2021条经验 获得超8个赞

尝试这几行代码:


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]


查看完整回答
反对 回复 2023-12-29
?
Helenr

TA贡献1780条经验 获得超3个赞

如果您尝试从文件中读取该段落:


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]


查看完整回答
反对 回复 2023-12-29
  • 2 回答
  • 0 关注
  • 52 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信